Skip to content
ClapelloNotes by Barath
ReactCh 14 · 1/6
Beginner4 min readUpdated

React / 76

Responding to events

TL;DR

Give onClick, onChange and friends a function. React calls it when the event happens and passes an event object describing what happened.

Hand React a function

LikeButton.jsx
export default function LikeButton() {
  function handleClick() {
    alert("Thanks for the like!");
  }
 
  return <button onClick={handleClick}>Like</button>;
}
  • The prop is camelCase: onClick, onChange, onSubmit, onKeyDown.
  • Its value is a function in curly braces, not a string of code like HTML's onclick="...".
  • The handler lives inside the component, so it can read the component's props and state.
  • For one-liners, write it inline: onClick={() => alert("Thanks!")}.

Pass it, don't call it

This is the most common beginner bug in React, and the difference is just two characters:

Pass it

your JSX

onClick={handleClick}
React renders

during render

React stores the function. Nothing runs yet.
later, the user clicks

on click

React calls handleClick(e). The alert shows.

Call it

your JSX

onClick={handleClick()}
React renders

during render

handleClick runs now, on every render. onClick gets its return value: undefined.
later, the user clicks

on click · bug

Nothing happens. There is no function to call.
Curly braces run their JavaScript right away, during render. Without (), you hand React the function itself. With (), you hand it whatever the function returns.

Don't

Calling it during render

<button onClick={handleClick()}>Like</button>

The alert pops up as the page loads, and clicking does nothing. If the handler sets state, every render sets state again, and React stops with "Too many re-renders".

Do

Passing it (or wrapping it)

<button onClick={handleClick}>Like</button>
<button onClick={() => handleClick()}>Like</button>

Both hand React a function. Nothing runs until the click.

The event object

React calls your handler with one argument: an event object that describes what happened. By convention it's called e.

<input onChange={(e) => console.log(e.target.value)} />

e.target is the element where the event happened, so e.target.value is the text in the box right now. You'll also meet e.preventDefault() and e.stopPropagation() soon. The next topic opens the event object up properly.

Passing arguments

Often one handler serves many buttons and needs to know which one was clicked. Wrap the call in an arrow function:

Menu.jsx
import { useState } from "react";
 
const dishes = [
  { id: "d1", name: "Masala dosa" },
  { id: "d2", name: "Paneer tikka" },
];
 
export default function Menu() {
  const [cart, setCart] = useState([]);
  function handleAdd(id) {
    setCart([...cart, id]);
  }
 
  return (
    <ul>
      {dishes.map((dish) => (
        <li key={dish.id}>
          {dish.name}
          <button onClick={() => handleAdd(dish.id)}>Add</button>
        </li>
      ))}
      <li>{cart.length} in cart</li>
    </ul>
  );
}

One handler, three buttons

Try it
onClick={() => handleAdd(dish.id)}
  • Masala dosa id: "d1"
  • Paneer tikka id: "d2"
  • Gulab jamun id: "d3"
  1. Click an Add button.
Every button shares handleAdd. The arrow in onClick remembers which dish it belongs to, and only runs (calling handleAdd) when you click.

Need the event too? Pass it along: onClick={(e) => handleAdd(dish.id, e)}.

Naming: handleX inside, onX as a prop

You can pass handlers down to your own components as props, just like any other value:

DishRow.jsx
function AddButton({ onAdd, children }) {
  return <button onClick={onAdd}>{children}</button>;
}
 
export default function DishRow() {
  function handleAddDosa() {
    alert("Dosa added");
  }
  return <AddButton onAdd={handleAddDosa}>Add dosa</AddButton>;
}
WhatConventionExamples
A function you writehandle + what happenedhandleClick, handleAddDosa, handleSubmit
A prop your component acceptson + what happenedonAdd, onSelect, onClose
A prop on a built-in elementfixed by ReactonClick, onChange, onSubmit, onBlur

Name your own props after what happened in your app (onAddToCart), not the browser event that caused it (onClick). Later you might trigger it from a keyboard shortcut too, and the name still fits.

Handlers can have side effects

Your component body must stay pure: same props and state in, same JSX out. Event handlers don't have that rule. They're the place to change state, call fetch, write to localStorage or log analytics, because they run because the user did something, not because React rendered.

Gotchas

Recall

Can you answer these?

0/4

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.