Handling Events

What this is. Event handlers are props: a camelCase name and a function as the value.

onClick, onChange, onSubmit, onKeyDown. There is no addEventListener to write and nothing to remove afterwards.

Pass the function, do not call it.

onClick={handleClick} hands React the function to call later.

onClick={handleClick()} calls it immediately, during the render, and gives React whatever it returned. If that handler sets state, you have an infinite loop and the error reads Too many re-renders.

When you need to pass an argument, wrap it: onClick={() => remove(id)}.

Try it

Change onClick={() => record('clicked')} to onClick={record('clicked')} and see the page break immediately. That error message is worth recognizing.

loading editor…

loading React…

✦ A click handler on a div is not a button

A div with onClick cannot be reached by keyboard, is not announced as interactive, and cannot be activated with Enter or Space. A button gives you all of that for free. If it navigates somewhere, use a link. If it performs an action, use a button. Recreating that behavior on a div takes tabIndex, a role, and two key handlers, and is still worse than the element that already does it.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Controlled Inputs →
← Back