React Reference ยท react-dom Client APIs
React createPortal() function
Reference for createPortal from react-dom: render children into a different DOM node, keep context and event bubbling, and avoid clipping and z-index traps.
createPortal(children, domNode, key?) renders React children into a DOM node that is outside the parent component's own DOM element. In the React tree the portal stays where you wrote it, so props, context and state flow as usual; in the browser DOM the output lands in the node you chose.
Portals solve layout problems: modals, tooltips, dropdowns and toasts that must escape a parent with overflow: hidden, a transform, or a low stacking context. You usually portal to document.body or to a dedicated container element.
import { createPortal } from 'react-dom'; function Tooltip({ children }) { return createPortal(<div className="tip">{children}</div>, document.body); }
Try it
Syntax
createPortal(children, domNode, key?)
| Parameter | Description |
|---|---|
children |
Anything React can render: JSX, a string, a fragment, an array. |
domNode |
An existing DOM node, such as document.body or an element you created. |
key |
Optional string used as the portal's key. |
Returns a React node. It must be placed in a component's output (returned or nested in JSX) to take effect.
Usage notes
- Events bubble through the React tree, not the DOM tree. A click inside the portal reaches
onClickhandlers on React ancestors, even though the DOM nodes are elsewhere (first example). Callevent.stopPropagation()if you do not want that. - Context works across the portal, because context follows the React tree (second example).
- The target node must exist when the component renders. Create it beforehand, or read it in an effect and store it in state.
- Do not portal into a node React itself renders. Portal to an element outside any React-managed output.
- On the server there is no DOM, so
document.bodyis undefined. Render portals only on the client, for example after a mount flag, or when the modal is open. - Portals do not fix accessibility on their own. A modal still needs focus management,
aria-modal, Escape to close, and background content that is inert. The native<dialog>element handles much of this. - CSS inheritance follows the DOM, so the portal content does not inherit the styles of its React parent; it inherits from the new location.
- Unmounting the portal component removes its content from the target node.
- Many portals can target the same node. Give each a
keywhen they appear in lists.