Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 132 ยท State and Events

Handling Events

Learn how to handle events in React 19 - onClick and onChange, the event object, passing handlers, preventDefault, stopPropagation, bubbling and capture, and keyboard and pointer events.

A page that never reacts to the user is a poster. Clicks, key presses, form submissions and pointer movements are how people talk to your UI, and React gives you a consistent way to listen: you attach a handler function to an element through a prop such as onClick. When the event happens, React calls your function. Inside it you can read the event, call other functions, and (as you will see in the next lessons) update state, which makes React render again.

This lesson covers how to write handlers, what the event object contains, the most important mistake beginners make with them, how events travel through the tree (bubbling and capture), and the keyboard and pointer events you will use most.

Your first handler

You write the handler as a function and pass it as the value of an event prop. The prop names are camelCase versions of the DOM event names: onClick, onChange, onSubmit, onKeyDown, onMouseEnter, onFocus, and so on.

Click handlers

Click each button and watch the console panel. Two styles appear here, and both are fine:

  • A named handler (handleClick) declared inside the component. It can read the component's props and state, because it is a closure over the values of that render. By convention its name starts with handle.
  • An inline arrow function for very short bodies.

By convention the prop that receives a handler starts with on (onClick) and the function you pass starts with handle (handleClick).

Pass the function, do not call it

This is the number one event mistake. The prop wants a function, not the result of calling one.

Passing versus calling a handler (fails on purpose)

When the component renders, sayHi() runs immediately and logs. The handler React receives is the string 'hi', not a function, so clicking the second button throws an error. The console shows "Expected onClick listener to be a function, instead got a value of string type." If the called function sets state, you get an infinite render loop; we meet that error in The Rules of Hooks and Common Hook Errors.

The same rule applies when a handler needs arguments. Wrap the call in an arrow function so you pass a function:

JSX
<button onClick={() => handleDelete(item.id)}>Delete</button>   {/* correct */}
<button onClick={handleDelete(item.id)}>Delete</button>         {/* runs during render */}

The event object

React calls your handler with one argument: an event object. It is a SyntheticEvent, a thin wrapper around the browser's native event with the same interface across browsers. You can read familiar properties: e.target (the element that was actually hit), e.currentTarget (the element whose handler is running), e.key, e.clientX, e.shiftKey, and so on. The original browser event is available as e.nativeEvent if you need it, which is rare.

Reading the event object

For inputs, e.target.value is the current text, e.target.checked the state of a checkbox. We build on this in Controlled Inputs and Forms. useState is covered in the next lesson, so for now read it as "a value that React remembers and that triggers a new render when you set it".

Older React versions pooled event objects and cleared them after the handler returned, so reading e inside a setTimeout gave null values. React 17 removed pooling. In modern React the event object stays valid, but it is still good practice to copy the values you need (const value = e.target.value) before an await or timeout.

Default actions and preventDefault

Browsers have built-in behaviors: a link navigates, a form submits and reloads the page, a checkbox toggles. e.preventDefault() cancels the browser's default action but lets your code run. In React you almost always handle form submission this way.

preventDefault on a form and a link

Use onSubmit on the <form> rather than onClick on the submit button: it also catches submission with the Enter key. Note that React 19 adds a newer way to handle forms, the action prop, covered in Form Actions in React 19.

Bubbling, stopPropagation and capture

Most DOM events bubble: after firing on the target element, the event travels up through each parent, calling matching handlers on the way. React follows the same model for its own tree. Clicking a button inside a card inside a panel triggers the button's onClick, then the card's, then the panel's.

Watching an event bubble

The first button logs button, middle div, outer div, in that order, from the inside out. The second calls e.stopPropagation(), so only stopped button is logged and the parents never hear about it.

Use stopPropagation sparingly. It is tempting, but it also hides events from legitimate listeners higher up (analytics, "click outside to close" menus). Prefer designing handlers so that parents ignore events they do not care about, for example by checking e.target === e.currentTarget.

If you need to react before the target does, add Capture to the prop name: onClickCapture. The capture phase runs from the outside in, before the bubble phase. You will rarely need it, but it is the right tool for something like "log every click inside this region, even if a child stops propagation".

preventDefault and stopPropagation are different things. preventDefault stops the browser's own behavior (navigation, submit). stopPropagation stops the event from reaching parent handlers. Calling one does not call the other.

Keyboard events

onKeyDown and onKeyUp give you e.key (the logical key, like 'Enter', 'Escape', 'a', 'ArrowDown') and e.code (the physical key position, like 'KeyA'). Use e.key for shortcuts that depend on what the key means. Avoid the deprecated keyCode, and prefer onKeyDown over onKeyPress, which is deprecated.

Keyboard handling: Enter to add, Escape to clear

A click handler on a <div> is not keyboard accessible; use a real <button> (or <a>) for anything clickable so that Enter, Space and focus work for free. Add custom key handling only for enhancements such as shortcuts or arrow-key navigation. The key={index} here is only acceptable because this list never reorders or deletes; see Rendering Lists and Keys.

Pointer and mouse events

onPointerDown, onPointerMove and onPointerUp unify mouse, touch and pen into one family and are preferred over onMouseDown and friends for new code. onMouseEnter and onMouseLeave do not bubble (they fire only for the element itself), which is usually what you want for hover effects. The event carries coordinates: clientX/clientY relative to the viewport, and e.currentTarget.getBoundingClientRect() lets you convert them.

Pointer position inside a box

Notice that e.currentTarget is the grey box (where the handler is attached), even if the pointer is over a child, and that every pointer move calls setPos, which renders again. High-frequency events like pointermove and scroll are fine for small components, but keep the work in the handler cheap.

Mouse, touch, clipboard, scroll and focus events

The families above cover most handlers. The rest of the event props are worth knowing by name, because each has one behavior that surprises people.

Prop When it fires Worth knowing
onMouseEnter / onMouseLeave The pointer enters or leaves the element Do not bubble; fire once per entry, not per child.
onMouseOver / onMouseOut Same, but for any child too These do bubble, so moving between children fires them again.
onMouseMove, onMouseUp Mouse position and release Prefer the pointer events for new code.
onTouchStart, onTouchMove, onTouchEnd, onTouchCancel A finger touches, moves, lifts, or the system interrupts onTouchCancel fires when a call or a scroll takes over; clean up there too.
onCopy, onCut, onPaste The user copies, cuts or pastes e.clipboardData holds the data. Call preventDefault() to replace what is copied or to block a paste.
onScroll A scrollable element scrolls Does not bubble in React: attach it to the element that scrolls.
onFocus / onBlur An element or any descendant gains or loses focus React's versions do bubble (they use focusin and focusout).
onInput and onChange The value of a form control changes In React, onChange fires on every keystroke, like the native input event.
onClickCapture, onFocusCapture, ... Same event, capture phase See bubbling and capture above.

Three of these deserve a closer look.

onChange is not the native change event. In plain HTML, change fires when a text field loses focus after being edited. React's onChange fires on every keystroke, which is what you want for controlled inputs. onInput behaves almost the same in React, so there is no reason to use it except when you match code from outside React.

onKeyPress is deprecated. The browser stopped recommending it years ago (it does not fire for keys like Escape or the arrows, and its key codes are inconsistent). Use onKeyDown, and onKeyUp when you need the release.

Touch events and pointer events overlap. On a touch screen a tap produces touch events, then pointer events, then simulated mouse events. If you handle all three families you will run your code several times. Use pointer events for dragging and drawing, and keep onTouch* for gestures that really need e.touches (several fingers at once). The drag and gestures lesson goes deeper.

A tour of less common events

Because onScroll and onMouseMove can fire dozens of times per second, keep these handlers cheap and avoid triggering large re-renders from them. Transitions and virtualization are the tools for the heavy cases.

Double click, context menu and mouse buttons

Three more mouse events are common in interfaces that feel like desktop software:

  • onDoubleClick fires after two quick clicks. Both single clicks fire first, so an element with both onClick and onDoubleClick runs the click handler twice before the double-click handler. Use it for "edit in place" (double-click a label to turn it into an input), and always offer a keyboard alternative such as Enter or an Edit button, because double-clicking is hard on touch screens and for some motor impairments.
  • onContextMenu fires on a right click (or the keyboard menu key). Call e.preventDefault() to suppress the browser menu and show your own.
  • onMouseDown and onMouseUp fire when a button goes down and up, before click. e.button tells you which one: 0 main, 1 middle, 2 secondary. e.buttons is a bit mask of what is held right now, and e.detail is the click count (1, 2, 3...).
Double click, right click and buttons

The renaming input handles Enter by calling blur(), which commits through onBlur, so there is only one place that saves. The yellow label has tabIndex={0} and an Enter handler, which is the keyboard path to the same action.

Preventing default behavior in a callback

preventDefault() was introduced earlier for forms and links. Two more cases are worth knowing. React attaches its onWheel, onTouchStart and onTouchMove listeners as passive, so calling preventDefault() there does nothing (the browser logs a warning); to stop scrolling you need a native listener added with { passive: false } in an effect, or the CSS property touch-action. And returning false from a handler does not cancel anything in React, unlike old inline HTML handlers: always call e.preventDefault() explicitly.

Passing handlers down and naming

Handlers are ordinary values, so a parent can define one and hand it to a child as a prop. The child decides when to call it; the parent decides what happens. This is how "events flow up" in React:

JSX
function Toolbar({ onSave }) {
  return <button type="button" onClick={onSave}>Save</button>;
}
function Editor() {
  function handleSave() { /* ... */ }
  return <Toolbar onSave={handleSave} />;
}

Name the prop after what happened from the child's point of view (onSave, onSelect, onClose), not after what the parent will do. That keeps the child reusable.

Note one thing: built-in DOM components like <button> only accept event props that exist on them. If you write <Toolbar onClick={...} /> on your own component, onClick is simply a prop called onClick; nothing happens unless Toolbar passes it on to a DOM element.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which is the correct way to run handleDelete(7) when a button is clicked?

    The prop needs a function. Wrapping the call in an arrow function creates one. Writing handleDelete(7) directly calls it during render.
  2. 2. What does e.preventDefault() do inside a form's onSubmit handler?

    preventDefault cancels the browser's built-in behavior. Stopping parent handlers is the job of stopPropagation.
  3. 3. A button inside a div; both have onClick handlers. The user clicks the button and the button's handler does not call stopPropagation. What happens?

    Events bubble from the target outwards, so the innermost handler runs first and each parent's handler follows.
  4. 4. Which prop would you use to run a handler during the capture phase?

    Appending Capture to an event prop name (onClickCapture, onKeyDownCapture) registers the handler for the capture phase, which goes from the outermost element inward.
  5. 5. Why should you prefer a real button over a clickable div?

    Native interactive elements come with focus, keyboard activation and correct semantics. A div needs extra roles, tabIndex and key handling to match.

Summary

  • Attach handlers with camelCase props such as onClick, onChange, onSubmit, onKeyDown and onPointerMove.
  • Pass a function (onClick={handle} or onClick={() => handle(id)}); never call it in the JSX.
  • Handlers receive a SyntheticEvent with target, currentTarget, key and friends; read input values from e.target.value.
  • preventDefault() cancels the browser's default action; stopPropagation() stops bubbling; add Capture to listen on the way down.
  • Use real <button> and <form onSubmit> elements so keyboard users are covered.
  • Name handler props onSomething and the functions that you pass handleSomething.

Next: State with useState