Responding to Events·续
That event object also lets you stop the propagation. If you want to prevent an event from reaching parent components, you need to call e.stopPropagation() like this Button component does:
function Button({ onClick, children }) {
return (
<button onClick={e => {
e.stopPropagation();
onClick();
}}>
{children}
</button>
);
}
export default function Toolbar() {
return (
<div className="Toolbar" onClick={() => {
alert('You clicked on the toolbar!');
}}>
<Button onClick={() => alert('Playing!')}>
Play Movie
</Button>
<Button onClick={() => alert('Uploading!')}>
Upload Image
</Button>
</div>
);
}
.Toolbar {
background: #aaa;
padding: 5px;
}
button { margin: 5px; }
When you click on a button:
- React calls the
onClickhandler passed to<button>. - That handler, defined in
Button, does the following: - Calls
e.stopPropagation(), preventing the event from bubbling further. - Calls the
onClickfunction, which is a prop passed from theToolbarcomponent. - That function, defined in the
Toolbarcomponent, displays the button's own alert. - Since the propagation was stopped, the parent
<div>'sonClickhandler does not run.
As a result of e.stopPropagation(), clicking on the buttons now only shows a single alert (from the <button>) rather than the two of them (from the <button> and the parent toolbar <div>). Clicking a button is not the same thing as clicking the surrounding toolbar, so stopping the propagation makes sense for this UI.
[!INFO]
Capture phase events
In rare cases, you might need to catch all events on child elements, even if they stopped propagation. For example, maybe you want to log every click to analytics, regardless of the propagation logic. You can do this by adding
Captureat the end of the event name:
<div onClickCapture={() => { /* this runs first */ }}>
<button onClick={e => e.stopPropagation()} />
<button onClick={e => e.stopPropagation()} />
</div>
Each event propagates in three phases:
- It travels down, calling all
onClickCapturehandlers.- It runs the clicked element's
onClickhandler.- It travels upwards, calling all
onClickhandlers.Capture events are useful for code like routers or analytics, but you probably won't use them in app code.
Passing handlers as alternative to propagation
Notice how this click handler runs a line of code and then calls the onClick prop passed by the parent:
```js {4,5} function Button({ onClick, children }) { return ( ); }
You could add more code to this handler before calling the parent `onClick` event handler, too. This pattern provides an *alternative* to propagation. It lets the child component handle the event, while also letting the parent component specify some additional behavior. Unlike propagation, it's not automatic. But the benefit of this pattern is that you can clearly follow the whole chain of code that executes as a result of some event.
If you rely on propagation and it's difficult to trace which handlers execute and why, try this approach instead.
### Preventing default behavior
Some browser events have default behavior associated with them. For example, a `<form>` submit event, which happens when a button inside of it is clicked, will reload the whole page by default:
```js
export default function Signup() {
return (
<form onSubmit={() => alert('Submitting!')}>
<input />
<button>Send</button>
</form>
);
}
button { margin-left: 5px; }
You can call e.preventDefault() on the event object to stop this from happening:
export default function Signup() {
return (
<form onSubmit={e => {
e.preventDefault();
alert('Submitting!');
}}>
<input />
<button>Send</button>
</form>
);
}
button { margin-left: 5px; }
Don't confuse e.stopPropagation() and e.preventDefault(). They are both useful, but are unrelated:
e.stopPropagation()stops the event handlers attached to the tags above from firing.e.preventDefault()prevents the default browser behavior for the few events that have it.
Can event handlers have side effects?
Absolutely! Event handlers are the best place for side effects.
Unlike rendering functions, event handlers don't need to be pure, so it's a great place to change something—for example, change an input's value in response to typing, or change a list in response to a button press. However, in order to change some information, you first need some way to store it. In React, this is done by using state, a component's memory. You will learn all about it on the next page.
- You can handle events by passing a function as a prop to an element like
<button>. - Event handlers must be passed, not called!
onClick={handleClick}, notonClick={handleClick()}. - You can define an event handler function separately or inline.
- Event handlers are defined inside a component, so they can access props.
- You can declare an event handler in a parent and pass it as a prop to a child.
- You can define your own event handler props with application-specific names.
- Events propagate upwards. Call
e.stopPropagation()on the first argument to prevent that. - Events may have unwanted default browser behavior. Call
e.preventDefault()to prevent that. - Explicitly calling an event handler prop from a child handler is a good alternative to propagation.
Fix an event handler
Clicking this button is supposed to switch the page background between white and black. However, nothing happens when you click it. Fix the problem. (Don't worry about the logic inside handleClick—that part is fine.)
```js {expectedErrors: {'react-compiler': [5, 7]}} export default function LightSwitch() { function handleClick() { let bodyStyle = document.body.style; if (bodyStyle.backgroundColor === 'black') { bodyStyle.backgroundColor = 'white'; } else { bodyStyle.backgroundColor = 'black'; } }
return ( ); }
The problem is that `<button onClick={handleClick()}>` _calls_ the `handleClick` function while rendering instead of _passing_ it. Removing the `()` call so that it's `<button onClick={handleClick}>` fixes the issue:
```js
export default function LightSwitch() {
function handleClick() {
let bodyStyle = document.body.style;
if (bodyStyle.backgroundColor === 'black') {
bodyStyle.backgroundColor = 'white';
} else {
bodyStyle.backgroundColor = 'black';
}
}
return (
<button onClick={handleClick}>
Toggle the lights
</button>
);
}
Alternatively, you could wrap the call into another function, like <button onClick={() => handleClick()}>:
export default function LightSwitch() {
function handleClick() {
let bodyStyle = document.body.style;
if (bodyStyle.backgroundColor === 'black') {
bodyStyle.backgroundColor = 'white';
} else {
bodyStyle.backgroundColor = 'black';
}
}
return (
<button onClick={() => handleClick()}>
Toggle the lights
</button>
);
}
Wire up the events
This ColorSwitch component renders a button. It's supposed to change the page color. Wire it up to the onChangeColor event handler prop it receives from the parent so that clicking the button changes the color.
After you do this, notice that clicking the button also increments the page click counter. Your colleague who wrote the parent component insists that onChangeColor does not increment any counters. What else might be happening? Fix it so that clicking the button only changes the color, and does not increment the counter.
```js src/ColorSwitch.js active export default function ColorSwitch({ onChangeColor }) { return ( ); }
```js src/App.js hidden
import { useState } from 'react';
import ColorSwitch from './ColorSwitch.js';
export default function App() {
const [clicks, setClicks] = useState(0);
function handleClickOutside() {
setClicks(c => c + 1);
}
function getRandomLightColor() {
let r = 150 + Math.round(100 * Math.random());
let g = 150 + Math.round(100 * Math.random());
let b = 150 + Math.round(100 * Math.random());
return `rgb(${r}, ${g}, ${b})`;
}
function handleChangeColor() {
let bodyStyle = document.body.style;
bodyStyle.backgroundColor = getRandomLightColor();
}
return (
<div style={{ width: '100%', height: '100%' }} onClick={handleClickOutside}>
<ColorSwitch onChangeColor={handleChangeColor} />
<br />
<br />
<h2>Clicks on the page: {clicks}</h2>
</div>
);
}
First, you need to add the event handler, like <button onClick={onChangeColor}>.
However, this introduces the problem of the incrementing counter. If onChangeColor does not do this, as your colleague insists, then the problem is that this event propagates up, and some handler above does it. To solve this problem, you need to stop the propagation. But don't forget that you should still call onChangeColor.
```js src/ColorSwitch.js active export default function ColorSwitch({ onChangeColor }) { return ( ); }
```js src/App.js hidden
import { useState } from 'react';
import ColorSwitch from './ColorSwitch.js';
export default function App() {
const [clicks, setClicks] = useState(0);
function handleClickOutside() {
setClicks(c => c + 1);
}
function getRandomLightColor() {
let r = 150 + Math.round(100 * Math.random());
let g = 150 + Math.round(100 * Math.random());
let b = 150 + Math.round(100 * Math.random());
return `rgb(${r}, ${g}, ${b})`;
}
function handleChangeColor() {
let bodyStyle = document.body.style;
bodyStyle.backgroundColor = getRandomLightColor();
}
return (
<div style={{ width: '100%', height: '100%' }} onClick={handleClickOutside}>
<ColorSwitch onChangeColor={handleChangeColor} />
<br />
<br />
<h2>Clicks on the page: {clicks}</h2>
</div>
);
}
