Sub topic 10
Stopping propagation
This chapter covers how to keep an event from reaching parent handlers, and when you should avoid doing that. It assumes you can write onClick handlers, read the event object, and know that most events bubble from the target element up through its ancestors. You should also be comfortable with useState and with passing props between components.
What propagation means in React
When you click a button inside a div, the browser fires the click on the button first. The event then travels up to the div, and then up to each further ancestor. This is bubbling. React follows the same order for the handlers you attach in JSX. If both the button and the div have onClick, both run, button first.
Often that is what you want. Sometimes a child element needs to handle an event without the parent also reacting. A "Delete" button inside a clickable table row is the standard case. Clicking Delete should not also open the row.
Calling stopPropagation
The event object React passes to your handler has a stopPropagation() method. Calling it prevents the event from reaching handlers on ancestor elements.
function Toolbar() {
return (
<div onClick={() => console.log('toolbar clicked')}>
<button
onClick={e => {
e.stopPropagation();
console.log('button clicked');
}}
>
Click me
</button>
</div>
);
}Clicking the button logs only button clicked. Without the stopPropagation() call, you would see button clicked followed by toolbar clicked. Clicking the div outside the button still logs toolbar clicked, because that click never passed through the button's handler.
A realistic example: a clickable card with an inner button
Here is a card that opens a detail view when clicked. It also has a "Favorite" button that must not open the card.
import { useState } from 'react';
function ProductCard({ name }) {
const [opened, setOpened] = useState(false);
const [favorite, setFavorite] = useState(false);
function handleFavoriteClick(e) {
e.stopPropagation();
setFavorite(f => !f);
}
return (
<div className="card" onClick={() => setOpened(true)}>
<h3>{name}</h3>
<button onClick={handleFavoriteClick}>
{favorite ? 'Unfavorite' : 'Favorite'}
</button>
{opened && <p>Details for {name}</p>}
</div>
);
}The call to e.stopPropagation() sits in the child's handler, because the child decides that its event is not the parent's business. The parent card does not need to know the button exists.
Stopping propagation is not preventing default
These two methods are often confused, and they do unrelated things.
| Method | What it stops | Typical use |
|---|---|---|
| `e.stopPropagation()` | The event reaching other handlers up (or down) the tree | Inner button inside a clickable parent |
| `e.preventDefault()` | The browser's built-in action for the event | Stopping a form submit from reloading the page |
Calling one does not call the other. A click on a link inside a clickable card needs preventDefault() if you want to stop navigation, and stopPropagation() if you want to keep the card from reacting. If you need both, call both.
Capture handlers and stopping early
Every React event has two phases. First comes the capture phase, which runs from the root down to the target. Then comes the bubble phase, which runs from the target back up. Props such as onClick run in the bubble phase. Props with the Capture suffix, such as onClickCapture, run in the capture phase.
A parent can use a capture handler to intercept an event before any child sees it. If it calls stopPropagation() there, the event never reaches the child at all.
import { useState } from 'react';
function LockedPanel() {
const [locked, setLocked] = useState(true);
function blockWhileLocked(e) {
if (locked) {
e.stopPropagation();
}
}
return (
<div onClickCapture={blockWhileLocked}>
<button onClick={() => alert('Action ran')}>Run action</button>
<button onClick={() => setLocked(l => !l)}>
{locked ? 'Unlock' : 'Lock'}
</button>
</div>
);
}While the panel is locked, a click on either button is stopped in the capture phase. The Run action handler does not fire. The lock toggle does not fire either, so this component locks itself permanently. That is a real design bug, and it shows how blunt a capture-phase stop is. Capture handlers see every event beneath them, so a fix must be selective. For example, call stopPropagation() only when e.target is not the toggle button, or move the toggle outside the captured div.
Gotchas
Stopping propagation can break code elsewhere
Other code may depend on seeing your event. Common victims are:
- "Click outside to close" logic for dropdowns and menus.
- Analytics code that listens for clicks near the root.
- A parent component that tracks which element was last interacted with.
If a dropdown closes when the user clicks anywhere else on the page, and some inner element stops propagation, that inner element becomes a dead zone. Clicking it will not close the dropdown.
Prefer checking the target when you can
Instead of stopping the event in the child, the parent can ignore events it does not care about. e.target is the element that was actually clicked. e.currentTarget is the element whose handler is running.
function Overlay({ onClose, children }) {
function handleOverlayClick(e) {
if (e.target === e.currentTarget) {
onClose();
}
}
return (
<div className="overlay" onClick={handleOverlayClick}>
<div className="dialog">{children}</div>
</div>
);
}Clicking the dark background closes the dialog. Clicking inside the dialog does not, because e.target is then an element inside .dialog, not the overlay itself. Nothing in the tree stopped the event, so other listeners still see it. This pattern is usually safer than adding stopPropagation() to the dialog.
React events bubble through the component tree, including portals
With createPortal, a child can render into a different DOM node, such as document.body. A React event from inside the portal still bubbles to the React parent of the portal, even though the DOM elements are not nested. A click inside a portaled modal can therefore trigger an onClick on a component that rendered the modal. If that is unwanted, stop propagation at the portal's content root, or check e.target against e.currentTarget.contains(...) in the parent.
React and native listeners are not on the same timeline
React attaches its listeners to the root container, the DOM node you passed to createRoot. Since React 17, e.stopPropagation() in a React handler also calls stopPropagation() on the underlying native event. That has these consequences:
- Native listeners on
documentorwindowdo not run, because the event never gets above the root container. - Native listeners on elements between the target and the root run before your React handler. React cannot stop what has already happened.
- Other native listeners on the root container itself still run, because
stopPropagation()does not affect listeners on the same element. To stop them as well, calle.nativeEvent.stopImmediatePropagation(). It only affects listeners that were registered after React's own.
In React 16 and earlier, React listened on document, so a React stopPropagation() could not stop other document listeners. Older tutorials and Stack Overflow answers describe that behavior. Check which React version you are on before relying on them.
Do not use stopPropagation to hide a state problem
If a parent and a child both change the same state and you stop propagation to avoid a conflict, consider whether the state should live in one place. Lifting state up and passing a handler down, as in the earlier chapters on handlers as props, often removes the need to stop anything.
When to stop, and when not to
| Situation | Suggested approach |
|---|---|
| Inner button in a clickable row or card | `stopPropagation()` in the inner handler |
| Click on a modal backdrop closes the modal | Compare `e.target` with `e.currentTarget` in the parent |
| Disable a whole region temporarily | Capture handler with a narrow condition |
| Need to block listeners on `document` | `stopPropagation()` works in React 17+ |
| Outside-click logic exists elsewhere | Avoid stopping, or test the stopped region explicitly |
Exercise
A table row has onClick={() => openRow(id)}. Inside it, a "Delete" button has onClick={() => deleteRow(id)}. Clicking Delete deletes the row and then also opens it. Fix this without changing the row's handler, and say what else you would check if a dropdown elsewhere on the page stops closing when users click Delete.
Show answer
Change the button's handler to accept the event and call e.stopPropagation() before deleteRow(id): onClick={e => { e.stopPropagation(); deleteRow(id); }}. The click then never reaches the row's onClick. If the dropdown relies on a document-level click listener to close, the stopped event also never reaches it in React 17+, so the dropdown stays open. Fix that by closing the dropdown from inside the Delete handler, or by moving the outside-click logic to a capture-phase listener that runs before the stop.