Skip to content
Tutorials Center
My learning

Topics

React Reference ยท Props and Attributes

React event handler props

How event handler props like onClick and onChange work in React: camelCase names, passing functions, arguments, naming conventions and common mistakes.

You respond to user actions in React by passing a function to an event handler prop on a built-in element: onClick, onChange, onKeyDown, onSubmit and many more. The names are camelCase (onClick, not onclick) and the value is a function, not a string of code.

React calls your function with a SyntheticEvent object when the event happens. State updates inside the handler are batched, so the screen updates once after the handler finishes.

JSX
<button onClick={handleClick}>Save</button>
<button onClick={() => remove(item.id)}>Delete</button>

Try it

Passing a function, not calling it

A component can accept handlers as props too. By convention the prop is called onSomething and the function that handles it inside the parent is handleSomething.

A custom component with an onSelect prop

Syntax

JSX
<element onEvent={(event) => { ... }} />
<element onEventCapture={(event) => { ... }} />
Name Description
onClick, onDoubleClick, onContextMenu Mouse clicks.
onChange, onInput, onSubmit, onReset Form events.
onKeyDown, onKeyUp Keyboard events.
onFocus, onBlur Focus events (these bubble in React).
onPointerDown, onMouseEnter, onTouchStart Pointer, mouse and touch events.
onScroll, onWheel Scrolling.
handler argument A SyntheticEvent. Its return value is ignored.

Usage notes

  • Pass the function, do not call it. onClick={handleClick} is right. onClick={handleClick()} calls the function during rendering and passes its result (usually undefined) as the handler.
  • Arguments need a wrapper. To pass data, write onClick={() => handleAdd(5)}. Inline arrow functions are fine in nearly all cases; do not optimise them away without measuring.
  • Names are fixed for built-in elements. <button onPress={...}> does nothing. On your own components, the prop name is whatever you decide.
  • Returning false does not cancel the default action. Call event.preventDefault(); see stopPropagation and preventDefault.
  • Handlers can be async. React ignores the returned promise, so catch errors inside the handler.
  • Handlers are not run during rendering. They may contain side effects such as fetching, logging or updating state; render functions may not.
  • Handlers read the state of their render. After setCount(count + 1), count is still the old value in the same handler; use the updater form to chain updates.
  • Bubbling: events bubble up the React tree, so a parent's onClick also runs when a child is clicked.