Sub topic 12
Responding to events
This chapter covers how React components respond to user actions such as clicks, typing, and form submission. It assumes you know function components, JSX attributes, props, and JavaScript arrow functions. State with useState gets its own chapter next, but a small amount appears here because events are most useful when they change something.
How event handlers attach to elements
In plain HTML you might write onclick="save()" as a string. In JSX, an event handler is a camelCase attribute whose value is a function, passed inside curly braces.
function SaveButton() {
function handleClick() {
alert('Saved!');
}
return <button onClick={handleClick}>Save</button>;
}Three rules apply to every handler:
- The attribute name is camelCase:
onClick,onChange,onSubmit,onKeyDown,onMouseEnter. - The value is a function, not a string and not the result of calling a function.
- React calls the function for you when the event happens.
By convention, handlers defined inside a component are named handle plus the event, such as handleClick or handleSubmit. Props that receive handlers are named on plus the event, such as onSave.
Pass the function, do not call it
The most common mistake is calling the function while writing the JSX.
// Wrong: runs during render, and passes its return value to onClick
<button onClick={handleClick()}>Save</button>
// Right: passes the function itself
<button onClick={handleClick}>Save</button>With handleClick(), the call runs every time the component renders. The onClick prop then receives undefined, so clicking does nothing. If the handler sets state, this mistake can cause an infinite render loop.
When you need to pass an argument, wrap the call in an arrow function so that nothing runs until the click.
function ItemButton({ item, onSelect }) {
return <button onClick={() => onSelect(item.id)}>{item.name}</button>;
}A handler that changes what is on screen
A handler that only shows an alert is rarely useful. Handlers usually update state, and React then re-renders the component.
import { useState } from 'react';
function LikeButton() {
const [liked, setLiked] = useState(false);
function handleClick() {
setLiked(!liked);
}
return (
<button onClick={handleClick}>
{liked ? 'Unlike' : 'Like'}
</button>
);
}
export default function App() {
return <LikeButton />;
}The handler does not edit the page. It asks React to store a new value, and the component function runs again and returns new JSX. The next chapter explains this cycle in detail.
The event object
React calls your handler with one argument, a synthetic event. It wraps the browser's native event and gives the same interface in every browser. It has the familiar properties:
| Property or method | Purpose |
|---|---|
| `e.target` | The element where the event started |
| `e.currentTarget` | The element the handler is attached to |
| `e.preventDefault()` | Stops the browser's default action |
| `e.stopPropagation()` | Stops the event from reaching parent handlers |
| `e.key` | The key pressed, on keyboard events |
| `e.nativeEvent` | The underlying browser event |
Declare a parameter only when you need the event. A handler like function handleClick() {} is fine, because JavaScript ignores extra arguments.
Reading input values
Text fields fire onChange on every keystroke. Read the current text from e.target.value.
import { useState } from 'react';
function NameField() {
const [name, setName] = useState('');
function handleChange(e) {
setName(e.target.value);
}
return (
<label>
Name:
<input value={name} onChange={handleChange} />
<p>Hello, {name || 'stranger'}.</p>
</label>
);
}Here value={name} makes the input a controlled input: React state is the source of truth, and the field shows whatever state holds. If you set value without an onChange, the field becomes read-only and React warns you.
Note that React's onChange differs from the DOM change event. React's version fires on each input, like the DOM input event, not only when the field loses focus.
Preventing default behavior
Some events trigger browser behavior. A form submit reloads the page, and a link click navigates. Call e.preventDefault() to stop it.
import { useState } from 'react';
function SearchForm() {
const [query, setQuery] = useState('');
const [submitted, setSubmitted] = useState('');
function handleSubmit(e) {
e.preventDefault();
setSubmitted(query);
}
return (
<form onSubmit={handleSubmit}>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<button type="submit">Search</button>
{submitted && <p>You searched for: {submitted}</p>}
</form>
);
}Attach onSubmit to the <form>, not to the button. That way pressing Enter in the field also submits the form. Also, a <button> inside a form submits by default, so give non-submitting buttons type="button".
Event propagation
Most events bubble: after the handler on the target runs, the same event triggers handlers on each ancestor, up to the root. This is useful for grouping behavior, and surprising when you forget it.
function Toolbar() {
return (
<div onClick={() => alert('Toolbar clicked')}>
<button onClick={() => alert('Play clicked')}>Play</button>
<button
onClick={(e) => {
e.stopPropagation();
alert('Stop clicked');
}}
>
Stop
</button>
</div>
);
}Clicking Play shows two alerts: first "Play clicked", then "Toolbar clicked". Clicking Stop shows only "Stop clicked", because stopPropagation() ends the bubbling.
Use stopPropagation sparingly. Stopping events can break other code that listens higher up, such as a menu that closes on outside clicks. preventDefault and stopPropagation are independent: one cancels the browser's default action, the other cancels bubbling.
Two related details:
- To run a handler during the capture phase, which goes from the root down to the target, add
Captureto the name, as inonClickCapture. onScrolldoes not bubble in React.
Passing handlers through props
A child component usually should not decide what a click means. The parent supplies the behavior as a prop, and the child calls it. This keeps components reusable.
import { useState } from 'react';
function Button({ onPress, children }) {
return <button onClick={onPress}>{children}</button>;
}
export default function App() {
const [message, setMessage] = useState('Nothing yet');
return (
<>
<Button onPress={() => setMessage('Saved')}>Save</Button>
<Button onPress={() => setMessage('Deleted')}>Delete</Button>
<p>{message}</p>
</>
);
}Button is a custom component, so onPress is an ordinary prop name you choose. Only built-in elements such as <button> and <input> give special meaning to names like onClick. If you write <Button onClick={...}> on a custom component, nothing happens unless the component forwards that prop to an element.
Common errors
- Calling instead of passing.
onClick={handle()}runs at render time. UseonClick={handle}. - Using a string.
onClick="handle()"does not work in JSX. - Wrong casing.
onclickandonchangeare ignored or trigger a warning. UseonClickandonChange. - Forgetting
preventDefaulton forms. The page reloads and state is lost. - Controlled input without
onChange. The field cannot be typed into. - Not forwarding the prop. A custom component must pass the handler to an inner element for it to have any effect.
- Assuming state updates immediately. After
setCount(count + 1), the variablecountin the same handler still holds the old value. The new value appears on the next render.
Exercises
Exercise
This button is meant to show an alert when clicked, but the alert appears as soon as the page loads, and clicking does nothing. Why, and how do you fix it? <button onClick={alert('Hi')}>Greet</button>
Show answer
alert('Hi') is called during render, and its return value, undefined, becomes the onClick prop. Wrap the call in a function so it waits for the click: <button onClick={() => alert('Hi')}>Greet</button>.
Exercise
A <form onSubmit={handleSubmit}> reloads the page each time the user presses Enter. What single line should handleSubmit contain, and where?
Show answer
Call e.preventDefault() at the start of handleSubmit, where e is the event parameter. This stops the browser's default form submission, so React can handle the data itself.
Exercise
A card has onClick={openDetails}. Inside it is a "Delete" button with its own onClick={handleDelete}. Clicking Delete also opens the details. Why does this happen, and how do you stop it?
Show answer
The click bubbles from the button up to the card, so both handlers run. Call e.stopPropagation() inside handleDelete, which prevents the event from reaching the card's handler.