Table of Contents

About

This page is about DOM event handling in React.

The React event e is a synthetic event defined according to the W3C spec (no worry about cross-browser compatibility ??)

Example

Usage

Differences with the DOM event:

    • React events are named using camelCase, rather than lowercase.
    • With JSX you pass a function as the event handler, rather than a string.
  • prevent_default_behavior You cannot return false to prevent default behavior in React. You must call preventDefault explicitly.

Syntax

DOM
<button onclick="activateLasers()">
  Activate Lasers
</button>
React
<button onClick={activateLasers}>
  Activate Lasers
</button>

Prevent default behavior

To prevent the default link behavior of opening a new page, you can write:

function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }

  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
}

Typescript

With Typescript, you need to define that the event is a React event.

Otherwise, you get:

... is missing the following properties from type 'MouseEvent': offsetX, offsetY, x, y, and 14 more.

Example:

<tr onClick={(event: React.MouseEvent<HTMLTableRowElement, MouseEvent>) => onRowDoubleClick(event, ...)}>
 ....
</tr>

Documentation / Reference