Thuta Learning
React
BasicWeb DevelopmentIntermediate

Handling Events

ReactLesson 825 min

What you'll walk away with

  • Explain the difference between onClick={handleClick} (passing a function) and onClick={handleClick()} (calling it during render)
  • Pass arguments such as an id to a handler with an arrow function
  • Use the event object's target, preventDefault() and stopPropagation() correctly
  • Hand handlers down to child components as onSomething props

Explain it simply

Explain it simply

An event handler is an instruction you leave with React in advance: "when this button is clicked, do this". It is like a shop owner telling an assistant "open the door when a customer rings the bell". The assistant does not open the door when told; they open it when the bell rings.

In React you give that instruction through camelCase props such as onClick, onChange and onSubmit. The value of the prop must be a function, not a string. React calls that function only when the user actually clicks.

Problem → Why → Solution

The problem: the handler runs before anyone clicks

People coming from HTML hit two mistakes first. The first is writing a string like onclick="..."; React does not accept string handlers. The second is sneakier: adding () and calling the function. The counter below crashes as soon as the page opens with "Too many re-renders. React limits the number of renders to prevent an infinite loop."

Counter.jsx
import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  // HTML habit (does not work in React):
  // <button onclick="setCount(count + 1)">+1</button>

  // Bug: setCount(...) is CALLED while rendering, not on click
  return <button onClick={setCount(count + 1)}>Clicked {count} times</button>;
}

Why does it loop forever?

React evaluates the expression inside { } on every render. setCount(count + 1) runs immediately, changes state, which causes another render, which calls setCount again, forever. Passing a new function instead, onClick={() => setCount(count + 1)}, means the code runs only when a click happens.

Core concept: you hand over a function, React calls it later

An event handler is an ordinary function declared inside your component. By convention it is named with a handle prefix, such as handleClick or handleSubmit. Writing onClick={handleClick} in JSX means "keep this function and call it when a click happens". The missing parentheses matter: handleClick is the function value, while handleClick() is whatever the function returns.

To give a handler an argument, such as the id of the item to delete, wrap the call in an arrow function: onClick={() => handleDelete(item.id)}. The arrow function is created on every render, but it only runs on click. Because handlers live inside the component, they can read props and state directly through closures.

When React calls your handler, it passes an event object. This is a synthetic event that wraps the browser's native event and gives you the familiar members, e.target, e.currentTarget, e.preventDefault() and e.stopPropagation(), with the same behaviour in every browser. If you really need the raw browser event, it is available as e.nativeEvent.

Just like in the DOM, events bubble up the React tree: click a button and its own handler runs first, then the onClick of the div that wraps it. e.stopPropagation() stops the event from travelling further up, while e.preventDefault() stops the browser's default action, such as following a link or reloading the page on form submit. They are separate tools. Returning false, which worked in old HTML handlers, prevents nothing in React.

Handlers are the main home for side effects: changing state, sending a request, writing a log. The render function itself must stay pure. In development, Strict Mode calls component functions twice to catch impure rendering, but it does not run event handlers twice.

Mental model: register now, run on the event
  1. Render attaches a function to onClick
  2. The user clicks
  3. React calls the handler with an event
  4. The handler sets state; React re-renders

Nothing should run during render; you only hand the function over.

General pattern

jsx
function Component({ onSomething }) {
  function handleEvent(event) {
    // read event.target, call setState, call onSomething(...)
  }

  return (
    <element onEventName={handleEvent}>...</element>
    // with an argument: onEventName={() => handleEvent(value)}
  );
}

Declare the handler inside the component and pass it to the onEventName prop without parentheses. Wrap it in an arrow function when it needs an argument. A handler can also call an onSomething prop to notify the parent.

Example: a button that responds to a click

This is the simplest handler shape. handleClick is declared inside the component and handed to the button's onClick as a function reference. Notice that no alert appears while the component renders.

jsx
function MyButton() {
  function handleClick() {
    alert('Button was clicked!');
  }

  return (
    <button onClick={handleClick}>
      Click Me
    </button>
  );
}

Code breakdown

  1. Line 2function handleClick() {

    The handler is declared inside MyButton, so it could read props or state directly later. The handle prefix tells readers this is an event handler.

  2. Line 3alert('Button was clicked!');

    This is a side effect. Because it lives in a handler, it runs once per click, never during rendering.

  3. Line 7<button onClick={handleClick}>

    The camelCase onClick receives the function itself. Writing handleClick() instead would show the alert on every render and do nothing on click.

  4. Line 8Click Me

    Because this is a real <button>, Enter and Space on the keyboard trigger onClick too, not only the mouse.

You should see
A "Click Me" button renders. Nothing happens during rendering; each click opens a browser alert reading "Button was clicked!".

Propagation, preventDefault and handler props

In the Toolbar below, ToolButton does not decide what happens; it calls whatever function the parent passed as onPress. The toolbar div's onClick catches every click that bubbles up. The link uses preventDefault() to stop the browser from navigating.

Toolbar.jsx
function ToolButton({ label, onPress }) {
  return <button type="button" onClick={onPress}>{label}</button>;
}

export default function Toolbar({ onLog }) {
  function handleHelp(event) {
    event.preventDefault();    // stay on this page
    event.stopPropagation();   // the toolbar does not see this click
    onLog('help opened');
  }

  return (
    <div className="toolbar" onClick={() => onLog('toolbar clicked')}>
      <ToolButton label="Save" onPress={() => onLog('saved')} />
      <a href="/help" onClick={handleHelp}>Help</a>
    </div>
  );
}
Event propFires whenTypical use
onClickClick, or Enter/Space on a buttonButtons, menu items
onChangeEvery change of an input's valueControlled inputs
onSubmitA form is submittedSending forms (with preventDefault)
onKeyDownA key is pressed downEnter/Escape shortcuts
onFocus / onBlurAn element gains or loses focusShowing field validation

Capture phase

If a parent must see every click even when a child calls stopPropagation(), for example for analytics, use onClickCapture. Capture handlers run first, top-down.

In real projects

Where this shows up in real projects

Every interaction in an app starts with a handler. On a product list, each "Add to cart" button is onClick={() => addToCart(product.id)}; a comment box catches Enter in onKeyDown to send; a modal catches Escape to close.

In design systems, components like Button, IconButton and MenuItem carry no business logic of their own; they accept an onClick or onSelect prop and forward it to the real <button> inside. That split lets one visual button do different jobs on different screens. Analytics tracking appears both as an onClickCapture near the app root and as direct calls inside handlers.

In tests, React Testing Library's user-event simulates clicks and typing, and you assert on what changed on screen. Checking what the user sees is more trustworthy than calling the handler functions directly.

Common mistakes

Common mistakes

1. Calling the handler during render

onClick={handleDelete(id)} deletes the item on every render and leaves undefined as the click handler. With an argument, wrap it: onClick={() => handleDelete(id)}; without one, pass onClick={handleDelete} with no parentheses.

2. Forgetting preventDefault() on submit

Without event.preventDefault() in an onSubmit handler, the browser submits the form and reloads the whole page, wiping all state. return false; does not prevent it in React.

3. Making a div clickable instead of using a button

<div onClick={...}> only works with a mouse: it cannot be reached with Tab, cannot be pressed with Enter, and screen readers do not announce it as a button. Anything clickable should be a <button type="button">.

Best practices

Best practices

  • Name functions inside a component handleX and props received from a parent onX, so it is obvious which code is local and which came from outside.
  • Name handler props after what they mean in your app, like onSave or onSelect, not after the element that triggers them, like onButtonClick.
  • When a handler grows long, move its logic into a pure function and let the handler just call it and set state.
  • Always give buttons inside a form a type, because a button without one defaults to type="submit".

Mini challenge

Mini challenge: a player toolbar

Build a player panel with Play, Pause and Reset buttons. The panel counts every click that bubbles up to it, but the Reset click must not reach the panel.

  • A ToolButton component takes label and onPress props and renders a <button type="button">
  • Keep status ("stopped" / "playing" / "paused") and panelClicks in two pieces of state
  • The panel div's onClick adds 1 to panelClicks with an updater function
  • The Reset handler calls stopPropagation() and resets both pieces of state
Player.jsx
import { useState } from 'react';

// TODO: ToolButton({ label, onPress }) renders a <button type="button">
//       that calls onPress when clicked

export default function Player() {
  // TODO: status state (starts as 'stopped') and panelClicks state (starts at 0)

  function handleReset(event) {
    // TODO: keep this click away from the panel, then reset both values
  }

  return (
    <div>
      {/* TODO: count clicks that bubble up to this div */}
      {/* TODO: show "Status: ... | Panel clicks: ..." in a <p> */}
      {/* TODO: Play, Pause and Reset buttons */}
    </div>
  );
}

Expected: Initially: Status: stopped | Panel clicks: 0 After Play: Status: playing | Panel clicks: 1 After Pause: Status: paused | Panel clicks: 2 After Reset: Status: stopped | Panel clicks: 0

Show hint

Use an updater, setPanelClicks(c => c + 1), in the panel's handler. If Reset forgets stopPropagation(), the panel's +1 runs after setPanelClicks(0) and you end up with 1.

Show solution
Player.jsx
import { useState } from 'react';

function ToolButton({ label, onPress }) {
  return <button type="button" onClick={onPress}>{label}</button>;
}

export default function Player() {
  const [status, setStatus] = useState('stopped');
  const [panelClicks, setPanelClicks] = useState(0);

  function handleReset(event) {
    event.stopPropagation();
    setStatus('stopped');
    setPanelClicks(0);
  }

  return (
    <div className="panel" onClick={() => setPanelClicks((c) => c + 1)}>
      <p>Status: {status} | Panel clicks: {panelClicks}</p>
      <ToolButton label="Play" onPress={() => setStatus('playing')} />
      <ToolButton label="Pause" onPress={() => setStatus('paused')} />
      <ToolButton label="Reset" onPress={handleReset} />
    </div>
  );
}

Quick quiz 1 / 3

In <button onClick={save()}>Save</button>, when does save() run?

Quick quiz 2 / 3

In the challenge's Player, if Reset did not call stopPropagation(), what would Panel clicks show after Play then Reset?

Quick quiz 3 / 3

Each list item has a Delete button. How should it pass item.id to handleDelete?

What to remember

  • Event props are camelCase (onClick, onChange, onSubmit) and take a function, never a string.
  • onClick={handleClick} passes the function; onClick={handleClick()} calls it during render. Wrap calls with arguments in an arrow function.
  • preventDefault() stops the browser's default action; stopPropagation() stops bubbling.
  • Pass handlers down as onSomething props, and keep side effects in handlers rather than in render.

React Documentation — React

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Handling Events | Thuta Learning