createPortal(children, domNode, key?) from react-dom returns a React node. Wherever a component returns it, React renders children and places their DOM nodes inside domNode instead of inside the component's parent DOM element. The target must already exist; switching to a different node later recreates the portal's content.
A portal changes only the physical DOM placement. In every other way the children are still children of the component that rendered them:
- Context flows in: a
ThemeContextprovider above the component reaches components inside the portal. - React events bubble through the React tree. A click inside a portal rendered into
document.bodyreaches anonClickon the portal's React parent, although that<div>is nowhere near it in the DOM. - State and lifecycle belong to the owning component: the portal mounts and unmounts with it.
What follows the DOM tree instead: native listeners (addEventListener, contains() checks), CSS inheritance and selectors, and layout. That's the point of portals: content escapes an ancestor's overflow: hidden or a stacking context that would clip or bury a tooltip, menu or modal.
React's own events work because of delegation. Since React 17, React attaches its listeners to the root container instead of document; a portal's container is usually outside the root, so in React 19.3.1 mounting a portal also attaches React's listeners to that container. React then walks the fiber tree, not the DOM, to find handlers.
For modals, check whether you need a portal at all: <dialog> opened with showModal(), and the popover attribute, put an element in the browser's top layer, above every stacking context, from wherever it sits in the DOM. Portals are still useful for rendering into a specific node, including one owned by non-React code. Either way, the modal still needs focus and keyboard handling.