React / 76
Responding to events
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
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}during render
on click
Call it
your JSX
onClick={handleClick()}during render
on click · bug
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:
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 itonClick={() => handleAdd(dish.id)}- Masala dosa id: "d1"
- Paneer tikka id: "d2"
- Gulab jamun id: "d3"
- Click an Add button.
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:
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>;
}| What | Convention | Examples |
|---|---|---|
| A function you write | handle + what happened | handleClick, handleAddDosa, handleSubmit |
| A prop your component accepts | on + what happened | onAdd, onSelect, onClose |
| A prop on a built-in element | fixed by React | onClick, 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.
