Chapter 6 · Adding Interactivity
Responding to Events
Make things happen when the user clicks, types, hovers or submits.
- How to write and attach an event handler
- The #1 beginner bug:
onClick={fn()} - How to pass event handlers as props, and name them
- Event bubbling,
stopPropagation()andpreventDefault()
Adding an event handler
An event handler is a function that runs in response to something the user does. You write it, then pass it to a JSX element:
- Define a function inside the component. By convention its name starts with
handleplus the event:handleClick,handleMouseEnter,handleSubmit. - Pass it as a prop:
onClick={handleClick}.
You can also write it inline, which is handy for short handlers:
⚠️ Pass the function, don't call it
| ✅ Passing a function | 🔴 Calling a function |
|---|---|
onClick={handleClick} | onClick={handleClick()} |
onClick={() => alert('hi')} | onClick={alert('hi')} |
With parentheses, the function runs immediately, while rendering, not on click. And if it updates state, that triggers another render, which calls it again: an infinite loop ("Too many re-renders").
The rule: onClick needs a function to call later. To pass an argument, wrap the call in an arrow function: onClick={() => deleteItem(id)}.
Handlers can read props
Because handlers are defined inside the component, they can see its props and variables:
Passing event handlers as props
Often the parent decides what should happen, and the child just provides the button. Pass the handler down as a prop:
Now Button is reusable: it handles the look, and the parent supplies the behaviour. This is also the main way a child talks to its parent. The parent gives the child a function, and the child calls it.
Naming your own event props
For your own components, name event props on + something meaningful to your app, not just to the browser:
onSomething; the functions you pass are named handleSomething. For example: <Toolbar onPlayMovie={handlePlayMovie} />.Event propagation (bubbling)
An event starts at the element you clicked, then bubbles up through every parent, running their handlers too:
Clicking Play Movie shows "Playing!" and then "You clicked on the toolbar!".
Stopping propagation
Every handler receives an event object, usually called e. Call e.stopPropagation() to stop the event from reaching the parents:
A typical use is a modal: clicking the dark background closes it, but clicking inside the box shouldn't:
Preventing default browser behaviour
Some elements have built-in behaviour. For example, submitting a <form> reloads the whole page. Stop that with e.preventDefault():
| Method | What it stops |
|---|---|
e.stopPropagation() | Handlers on parent elements from running |
e.preventDefault() | The browser's built-in action (form reload, link navigation) |
Common events
| Prop | Fires when… | Typical element |
|---|---|---|
onClick | clicked or tapped | button, any element |
onChange | the value changes (on every keystroke) | input, textarea, select |
onSubmit | a form is submitted | form |
onMouseEnter / onMouseLeave | the pointer moves in or out | any element |
onKeyDown | a key is pressed | input, any focused element |
onFocus / onBlur | an element gains or loses focus | input |
More examples
Example 1: what's inside the event object?
Click the button: target is the button, but currentTarget is the div, because the click bubbled up to the div's handler.
Example 2: reacting to the keyboard
Example 3: passing an ID to the handler
The arrow function () => onPlay(song.id) "remembers" which song it belongs to.
Example 4: mouse enter and leave
Example 5: onChange on different inputs
Recap
- Handle events by passing a function:
onClick={handleClick}(no parentheses!). - Handlers are defined inside components, so they can read props.
- Pass handlers down as props named
onSomething. This is how children talk to parents. - Events bubble up.
e.stopPropagation()stops that;e.preventDefault()stops the browser's default action.
Exercises
1. Fix the handler
Show solution
Remove the parentheses: onClick={handleClick}. With (), it ran once during rendering and never on click.
2. Child → parent
Create a ColorButton with props color and onPick. When it's clicked, it calls onPick(color). In the parent, render three of them (red, green, blue), and have the parent alert the picked colour.
Show solution
3. A form that doesn't reload
Build a form with one input and a "Search" button. On submit, prevent the reload and alert "Searching…". Hint: read the value with new FormData(e.target).get('q') and give the input name="q".
Show solution
4. Say hello 🟢 easy
Create <HelloButton name="Asha" /> that alerts "Hello, Asha!" when clicked.
Show solution
5. Log every keystroke 🟢 easy
Make an input that logs its current value, and its length, to the console on every change.
Show solution
6. Submit on Enter 🟢 easy
Make an input that alerts "Sent: …" when the user presses Enter, and ignores the other keys.
Show solution
7. Media toolbar 🟡 medium
Create MediaControls with the props onPlay, onPause and onStop, which renders three buttons. In App, pass handlers that log "playing", "paused" and "stopped".
Show solution
8. Predict the bubbling 🟡 medium
What's logged when you click the button? Then change it so only "button" is logged.
Show solution
The order is button → middle → outer (from the inside out). To log only "button":
9. Confirm before leaving 🟡 medium
Make a link to https://react.dev that asks "Leave this page?" with window.confirm. If the user cancels, prevent the navigation.
Show solution
10. A reusable ConfirmButton 🔴 hard
Build <ConfirmButton message="Are you sure?" onConfirm={fn}>Delete account</ConfirmButton>. It asks for confirmation and calls onConfirm only when the user clicks OK. It also shouldn't let the click bubble up to its parents. Use it twice with different messages and actions.
Show solution
📖 Official docs: Responding to Events