Sub topic 6
Events bubble through the React tree
React portals change where an element appears in the DOM. They do not change where it sits in the React component tree. Events follow the component tree. This chapter explains what that means for click handlers, form submits and focus handlers, and how to write code that handles it correctly.
This chapter assumes you know function components, props and children, useState and useEffect, and how native DOM event bubbling works (an event fires on the target, then on each ancestor in turn). It also assumes you have seen createPortal in the earlier chapters.
The rule
When an event fires inside a portal, React bubbles it to the portal's React parents, not to the DOM parents of the portal container.
Here is the example from the topic plan:
import { createPortal } from 'react-dom';
function Parent() {
return (
<div onClick={() => console.log('Parent received the click')}>
<PortalButton />
</div>
);
}
function PortalButton() {
return createPortal(<button>Click me</button>, document.body);
}In the DOM, the <button> is a direct child of <body>. The <div> rendered by Parent is not its ancestor. A native addEventListener('click', ...) on that <div> would never fire for a click on the button. The React onClick on the same <div> does fire, because PortalButton is a child of Parent in the React tree.
How React implements this
React does not attach a listener to every element. It uses event delegation. It attaches one listener per event type to the root container you passed to createRoot. React also attaches listeners to each portal container, so events inside the portal are noticed.
When a native event arrives, React reads event.target and finds the matching component instance. It then walks up the React tree from that instance and calls the matching handlers (onClick, and the capture-phase onClickCapture first). The walk follows component parents. For a portal, the parent is the component that rendered createPortal.
This explains two things:
- Handlers on React ancestors fire even when the DOM ancestors are unrelated.
- The event object React gives you is a wrapper around the native event.
event.nativeEventis the real one.
React 17 and later attach listeners to the root container. React 16 attached them to document. This changes how React handlers interact with native document listeners, covered below.
A useful consequence: the backdrop pattern
The modal from the topic plan uses this behavior on purpose:
import { createPortal } from 'react-dom';
function Modal({ children, onClose }) {
return createPortal(
<div className="backdrop" onClick={onClose}>
<div
className="dialog"
role="dialog"
aria-modal="true"
onClick={(e) => e.stopPropagation()}
>
{children}
</div>
</div>,
document.body
);
}A click on the dark backdrop reaches onClose. A click inside the dialog is stopped at the dialog, so it never reaches the backdrop handler. This works inside the portal because both handlers are part of the same React subtree.
The same bubbling that lets this work also sends every click inside the dialog to whatever component rendered <Modal>, unless you stop it. That is the source of most surprises.
Surprise 1: the parent's handler fires for modal clicks
Suppose a card toggles itself open when clicked, and it contains a modal:
import { useState } from 'react';
function Card() {
const [expanded, setExpanded] = useState(false);
const [showModal, setShowModal] = useState(false);
return (
<div className="card" onClick={() => setExpanded((v) => !v)}>
<h2>Card (expanded: {String(expanded)})</h2>
<button
onClick={(e) => {
e.stopPropagation();
setShowModal(true);
}}
>
Open details
</button>
{showModal && (
<Modal onClose={() => setShowModal(false)}>
<p>Details</p>
</Modal>
)}
</div>
);
}Every click inside the modal, including the click on the backdrop, bubbles to the card's onClick. The card collapses or expands while the user is working in the dialog. The modal is visually separate from the card, but in the React tree it is a child of the card.
The simplest fix is to stop propagation at the portal boundary, inside the component that owns the portal:
import { createPortal } from 'react-dom';
function Modal({ children, onClose }) {
return createPortal(
<div
className="backdrop"
onClick={(e) => {
e.stopPropagation();
onClose();
}}
>
<div
className="dialog"
role="dialog"
aria-modal="true"
onClick={(e) => e.stopPropagation()}
>
{children}
</div>
</div>,
document.body
);
}Now no click leaves the modal through React bubbling. The parent no longer needs to know that a portal exists.
Which events to stop
Clicks are the common case, but all of these bubble through the React tree:
- Pointer and mouse events (
onMouseDown,onPointerDown,onMouseEnteris a special case, see below). - Keyboard events (
onKeyDown). A card with a keyboard shortcut handler also receives keys typed in a modal input. onFocusandonBlur. React's versions bubble, unlike the nativefocusandblur. They behave likefocusinandfocusout.onChange,onInputandonSubmit.
If you stop only onClick, a parent that listens to onKeyDown still sees keystrokes from the modal. Stop the events your parents may care about, or better, design parents so they check where an event came from.
Surprise 2: forms and submit events
A portal inside a <form> can put controls into the React form's event path, even though the DOM elements are outside it.
import { createPortal } from 'react-dom';
function SearchForm({ onSearch }) {
return (
<form
onSubmit={(e) => {
e.preventDefault();
onSearch();
}}
>
<input name="q" />
<Dialog />
</form>
);
}
function Dialog() {
return createPortal(
<form onSubmit={(e) => e.preventDefault()}>
<input name="note" />
<button type="submit">Save note</button>
</form>,
document.body
);
}Submitting the inner form calls the inner onSubmit, then bubbles through the React tree to the outer onSubmit, so onSearch runs too. The DOM has no nested forms (that would be invalid HTML), but React's tree does. If the inner handler should be final, call e.stopPropagation() there.
Note the reverse: a <button type="submit"> in a portal does not submit the outer form natively. The browser decides form ownership from the DOM, and the button is not inside the outer <form> element. Only React's synthetic event bubbling crosses the boundary.
Telling portal events from local events
Sometimes a parent should react only to events from its own DOM subtree. Compare currentTarget with target using DOM containment:
function Panel({ children }) {
function handleClick(event) {
if (!event.currentTarget.contains(event.target)) {
return; // the event came from a portal child
}
console.log('Clicked inside the panel DOM');
}
return <div onClick={handleClick}>{children}</div>;
}Inside a React handler, currentTarget is the DOM element the handler is attached to, and target is the DOM element where the event began. For an event from a portal, target is not a DOM descendant of currentTarget, so contains returns false. This approach is better than stopping propagation when the parent has no control over what its children render.
Native listeners behave differently
Native listeners follow the DOM tree. They do not see the React tree at all. This matters in two cases.
Outside-click detection
A common dropdown hook closes the menu when a click lands outside it:
import { useEffect, useRef } from 'react';
function useOutsideClick(onOutside) {
const ref = useRef(null);
useEffect(() => {
function handlePointerDown(event) {
if (ref.current && !ref.current.contains(event.target)) {
onOutside();
}
}
document.addEventListener('pointerdown', handlePointerDown);
return () => document.removeEventListener('pointerdown', handlePointerDown);
}, [onOutside]);
return ref;
}This hook breaks if the component renders a portal child (for example a nested submenu or a date picker popover). The submenu's DOM is not inside ref.current, so a click on it counts as outside and the whole menu closes. The fix is to treat the portal content as inside. Give the portal content its own ref and check both, or mark it with a data attribute and check event.target.closest('[data-layer]').
Interaction with React's `stopPropagation`
In React 17 and later, React listens on the root container (and portal containers). When your React handler calls e.stopPropagation(), React also calls stopPropagation() on the native event. That native event is then at the root or portal container, so listeners on elements above it, such as document, do not fire. A native listener on document may therefore miss events that a React handler stopped. In the modal above, the portal container is document.body, so the stop happens at body and document listeners do not see the click.
A native listener attached on an element below the container runs before React sees the event. Stopping propagation there prevents React handlers from running at all.
| Listener | Follows | Runs relative to React handlers |
|---|---|---|
| React `onClick` on an ancestor component | React tree | Bubbling order along the React tree |
| Native listener on a DOM ancestor below the container | DOM tree | Before React handlers |
| Native listener on `document` | DOM tree | After React handlers, unless React stopped the event |
Mouse enter and leave
onMouseEnter and onMouseLeave do not bubble in the DOM, and React does not bubble them either. They fire when the pointer enters or leaves the element in the React tree. For a portal, React handles the transition between a parent and its portal child. Moving the pointer from a button into its portal tooltip can fire onMouseLeave on the button in the DOM sense, while React's handling follows the component hierarchy. If hover behavior seems wrong, test it in the browser and prefer onPointerEnter and onPointerLeave on the portal content itself, with a short close delay, instead of relying on the parent's leave event.
Debugging checklist
When a handler fires unexpectedly or not at all, work through these questions:
- Is the handler a React prop or a native
addEventListener? Only React props follow the React tree. - Which component renders the
createPortalcall? Its ancestors are the ones that receive bubbled events. - Does anything call
stopPropagation? Check for it in React handlers on the way up. - Is a document-level listener using
containson a ref? Portal content fails that check. - Is the event one of those that bubbles in React but not in the DOM (
onFocus,onBlur)?
Summary of decisions
- Want a child of a portal to be isolated from the parent's event handlers? Stop propagation at the portal root, inside the component that creates the portal.
- Want a parent to ignore events from portal children? Check
event.currentTarget.contains(event.target). - Writing outside-click logic? Include the portal content in the "inside" check.
- Want events from a portal to reach a parent on purpose? Do nothing. That is the default.
Exercise
A Toolbar component has onKeyDown={handleShortcut} on its root <div>. It renders a <Modal> (which uses createPortal into document.body) containing a text input. Typing in the input triggers handleShortcut. Why does this happen, and how can you fix it without changing Toolbar?
Show answer
The modal is a child of Toolbar in the React tree, so keydown events from the input bubble through the React tree to Toolbar's onKeyDown, even though the input is in document.body in the DOM. Fix it inside Modal by adding onKeyDown={(e) => e.stopPropagation()} to the portal's root element. Then keystrokes stop at the modal and never reach Toolbar.
Exercise
A dropdown uses a document pointerdown listener with ref.current.contains(event.target) to close itself. A submenu is rendered with createPortal into document.body. Clicking a submenu item closes the whole dropdown before the item's onClick runs. Why, and what is one fix?
Show answer
The submenu's DOM nodes are not descendants of ref.current, so contains returns false and the hook treats the click as outside. One fix is to give the submenu root a ref or data attribute and treat clicks inside it as inside, for example by also checking event.target.closest('[data-submenu]') before calling onOutside.