React - Event

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





Discover More
How to create and handle an event in a React Functional Component?

This page shows you how to create and handle a React event in a React function component Result: Click on the link to see the event in action
React Class Component - Event

in the context of a A Toggle component that renders a button that lets the user toggle between “ON” and “OFF” states:



Share this page:
Follow us:
Task Runner