Sub topic 9
Bubbling and capture
This chapter covers how a React event travels through the component tree, and how to hook into each phase of that trip. It assumes you know JavaScript functions and arrow functions, basic JSX, components and props, and the basics of useState. It also assumes you have attached handlers with onClick and read the event object.
Why this matters
A click on a button is also a click on every element that contains the button. If a parent div has its own onClick, it has to find out about that click somehow. Bubbling and capture are the rules for how and when it finds out.
Most bugs in this area look the same. A handler runs when you did not expect it to, or it runs twice, or it runs in a surprising order. Once you know the three phases of an event, these bugs become easy to trace.
The three phases of an event
When a user clicks an element, the browser does not just notify that element. The event moves through the tree in three phases:
- Capture phase. The event travels down from the root of the document to the target's parent.
- Target phase. The event reaches the element that was actually clicked, called the target.
- Bubble phase. The event travels back up from the target to the root.
In React, the handlers you write with names like onClick run in the bubble phase. This is the default and the one you will use almost all the time.
Bubbling in practice
Here is a parent and child that both listen for clicks:
function Card() {
return (
<div onClick={() => console.log('card clicked')}>
<button onClick={() => console.log('button clicked')}>
Open
</button>
</div>
);
}Clicking the button logs two lines, in this order:
button clicked
card clickedThe target's handler runs first. Then the event bubbles to the div, and its handler runs. Clicking the empty area of the card logs only card clicked, because the button was never the target.
Two details are worth keeping in mind:
- The event object is the same one all the way up.
e.targetis always the element where the event started.e.currentTargetis the element whose handler is running right now. - Bubbling follows the React component tree, not just the DOM tree. This matters for portals, covered below.
target versus currentTarget
When you handle a bubbled event on a parent, these two properties differ:
function Menu() {
function handleClick(e) {
console.log('target:', e.target.tagName);
console.log('currentTarget:', e.currentTarget.tagName);
}
return (
<ul onClick={handleClick}>
<li>Home</li>
<li>Settings</li>
</ul>
);
}Clicking "Home" logs target: LI and currentTarget: UL. The ul owns the handler, so it is the current target. The li is where the click happened, so it is the target. This difference is what makes it possible to put one handler on a parent instead of one on each child.
Which events bubble
Most user interface events bubble: click, keydown, input, submit, and the pointer and mouse events. A few do not bubble in the browser, such as mouseenter, mouseleave, load, and scroll on elements. React smooths over some of this. For example, React's onFocus and onBlur do bubble, which matches the browser's focusin and focusout events. React also gives you onMouseEnter and onMouseLeave, which do not bubble and fire only for the element they are attached to.
If you expect an event to reach a parent and it never does, check whether that event type bubbles at all.
Capture handlers
Sometimes you need to see an event before the element underneath it does. For that, React provides a Capture variant of each handler: onClickCapture, onKeyDownCapture, onFocusCapture, and so on.
function Panel() {
return (
<div
onClickCapture={() => console.log('1. panel capture')}
onClick={() => console.log('4. panel bubble')}
>
<button
onClickCapture={() => console.log('2. button capture')}
onClick={() => console.log('3. button bubble')}
>
Go
</button>
</div>
);
}Clicking the button logs:
1. panel capture
2. button capture
3. button bubble
4. panel bubbleAll capture handlers run first, from the outside in. Then all bubble handlers run, from the inside out. The target element has both its capture and bubble handlers called at the target phase, capture first.
When capture is useful
Capture handlers are the less common tool. Reasonable uses include:
- Logging or analytics that must record every click, even if a child later stops propagation.
- Blocking interaction in a region, for example ignoring clicks inside a container that is temporarily disabled.
- Observing focus before a child reacts to it.
If you find yourself reaching for capture to solve an ordinary parent-child problem, a normal bubble handler or a prop is usually clearer.
Stopping propagation
Calling e.stopPropagation() prevents the event from continuing to the next element in its path. This is the subject of the next chapter in detail, but it matters here because it interacts with both phases.
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. The event stops at the button and never bubbles to the div.
If you call stopPropagation in a capture handler, the event stops before it reaches the target at all. Handlers lower in the tree, including the target's own onClick, never run.
function Locked({ children }) {
return (
<div onClickCapture={e => e.stopPropagation()}>
{children}
</div>
);
}Anything inside Locked is now unclickable from the point of view of React handlers. This is powerful, and it is also a common source of confusion later, because the child's handler fails silently. Use it deliberately and leave a comment explaining why.
Common gotchas
A parent handler fires when you click a child
This is bubbling working as designed. For example, a clickable table row with a delete button inside it will also trigger the row's handler. Fix it by stopping propagation in the button, or by checking e.target in the row handler:
function Row({ item, onOpen, onDelete }) {
return (
<tr onClick={() => onOpen(item.id)}>
<td>{item.name}</td>
<td>
<button
onClick={e => {
e.stopPropagation();
onDelete(item.id);
}}
>
Delete
</button>
</td>
</tr>
);
}Overusing stopPropagation
Stopping propagation can break code elsewhere that relies on seeing the event. Examples are a dropdown that closes when you click outside it, or an analytics wrapper. Prefer checking e.target or e.currentTarget in the parent when you can, and stop propagation only when you truly need to.
Portals bubble through the React tree
A portal renders its children into a different DOM node, such as document.body. Events from the portal content still bubble to the React parent of the portal, not to the DOM parent. A click inside a modal rendered through a portal will reach an onClick on the component that rendered the modal. This is often useful, but it can surprise you if you expected the DOM structure to decide.
Mixing React and native listeners
React handlers and listeners added with addEventListener do not share one ordering. React attaches its own listeners at the root container, so a native listener on an inner element runs before the React handler. A native listener on document runs after React's root listener handles the event. Calling stopPropagation in a React handler does not reliably stop native listeners placed higher than the React root. Be careful when you combine the two styles.
Checking the phase
If you are unsure which phase a handler runs in, e.eventPhase returns a number: 1 for capture, 2 for target, and 3 for bubble. Logging it inside a handler is a quick way to confirm your mental model. Note that with React's synthetic events, this value reflects React's own dispatch and can differ from what the underlying browser event reports, so treat it as a debugging hint and not as program logic.
Quick reference
| Handler prop | Phase | Order among ancestors |
|---|---|---|
| `onClickCapture` | Capture | Outermost first |
| `onClick` | Bubble | Innermost first |
| `e.target` | Not a phase | Element where the event started |
| `e.currentTarget` | Not a phase | Element whose handler is running |
Exercises
Exercise
A div has onClickCapture that logs "A" and onClick that logs "B". Inside it is a button with onClickCapture logging "C" and onClick logging "D". In what order are the lines logged when the button is clicked?
Show answer
A, C, D, B. Capture handlers run from the outside in (A, then C). Bubble handlers then run from the inside out (D, then B).
Exercise
A list item has an onClick that opens a detail view, and it contains a "Favorite" button. Clicking Favorite should toggle the favorite status without opening the detail view. What are two ways to do this?
Show answer
First, call e.stopPropagation() in the button's onClick so the event never reaches the list item. Second, in the list item's handler, check whether the click came from the button, for example with e.target.closest('button'), and return early if it did.
Exercise
A child's onClick never runs, and you see no errors. A parent contains onClickCapture={e => e.stopPropagation()}. Why does this happen, and how would you fix it?
Show answer
The capture handler runs before the event reaches the child and stops it there, so the child's bubble handler is never called. Remove the stopPropagation call, or restrict it with a condition (for example, only when the container is disabled).