Handling Events

Handling events with React elements is very similar to handling events on DOM elements. There are some syntax differences:

  • React events are named using camelCase, rather than lowercase.
  • With JSX you pass a function as the event handler, rather than a string.

For example, the HTML:

<button onclick="activateLasers()">
  Activate Lasers
</button>

is slightly different in React:

<button onClick={activateLasers}>  Activate Lasers
</button>

Another difference is that you cannot return false to prevent default behavior in React. You must call preventDefault explicitly. For example, with plain HTML, to prevent the default link behavior of opening a new page, you can write:

<a href="#" onclick="console.log('The link was clicked.'); return false">
  Click me
</a>

In React, this could instead be:

function ActionLink() {
  function handleClick(e) {    e.preventDefault();    console.log('The link was clicked.');  }
  return (
    <a href="#" onClick={handleClick}>      Click me
    </a>
  );
}

Here, e is a synthetic event. React defines these synthetic events according to the W3C spec, so you don’t need to worry about cross-browser compatibility. See the SyntheticEvent reference guide to learn more.

When using React, you generally don’t need to call addEventListener to add listeners to a DOM element after it is created. Instead, just provide a listener when the element is initially rendered.

When you define a component, a common pattern is for an event handler to be a function in the component. For example, this Toggle component renders a button that lets the user toggle between “ON” and “OFF” states:

function Toggle() {
  const [isToggleOn, setIsToggleOn] = useState(true);

  function handleClick() {    setIsToggleOn(!isToggleOn);  }
  return (
    <button onClick={handleClick}>      {isToggleOn ? 'ON' : 'OFF'}
    </button>
  );
}

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);

Try it on CodePen

Passing Arguments to Event Handlers

Inside a loop, it is common to want to pass an extra parameter to an event handler. For example, if id is the row ID, the following arrow functions technique would work:

<button onClick={(e) => deleteRow(id, e)}>Delete Row</button>

The e argument representing the React event will be passed as a second argument after the ID. With an arrow function, we have to pass it explicitly.