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.
<button onClick={handleClick}>Save</button> <button onClick={() => remove(item.id)}>Delete</button>
Try 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.
Syntax
<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 (usuallyundefined) 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
falsedoes not cancel the default action. Callevent.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),countis 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
onClickalso runs when a child is clicked.
Related
SyntheticEvent, Capture phase handlers,onChange,onSubmit- Lessons: Events, State updates