Capítulo 102 de 116

Chapter 102: createPortal

Core Idea

createPortal(children, domNode) renders a subtree into a DOM node located elsewhere in the document than where the calling component sits in the React tree — the standard way to escape a parent's CSS overflow/z-index stacking context (modals, tooltips, dropdowns) while keeping the component logically nested in React's tree.

Key Concepts

  • Signature: createPortal(children, domNode) — returns something you include in JSX like any other element; children renders as descendants of domNode in the actual DOM, while remaining a normal child in the React component tree (for context, event bubbling, and state purposes).
  • React tree position ≠ DOM position: event bubbling still follows the React tree, not the DOM tree — a click inside a portaled modal still bubbles up through its logical React ancestors' handlers, even though in the DOM it's physically rendered somewhere else entirely (commonly straight under <body>).
  • Typical use case: modals, tooltips, and dropdown menus that need to render outside a parent's overflow: hidden or stacking-context-limited container to display correctly on top of everything else, while still being written and composed as an ordinary nested component.
  • Context still flows through normally: Context providers above the portaling component in the React tree are still visible to the portaled content, since Context follows the React tree, not the DOM tree — this is one of the main reasons event bubbling and Context both "just work" through a portal despite the physical DOM relocation.

Code Examples

function Modal({ children }) {
  return createPortal(
    <div className="modal-overlay">{children}</div>,
    document.body
  );
}
  • What it demonstrates: Modal's content renders as a direct child of <body> in the DOM (escaping any ancestor's overflow/z-index constraints), while remaining a normal nested Modal component in React's tree for props/context/event purposes.

Key Takeaways

  1. A portal changes where in the DOM something renders, not where it sits in the React tree — event bubbling and Context both follow the React tree, unaffected by the physical DOM relocation.
  2. The go-to tool for modals/tooltips/dropdowns that need to escape a parent's clipping or stacking context.
  3. domNode typically needs to already exist in the DOM (commonly document.body, or a dedicated portal-root element) before the portal renders into it.

Connects To

  • Ch 20 (Responding to Events): the event-propagation model that continues to follow the React tree through a portal.
  • Ch 32 (Passing Data Deeply with Context): why Context still reaches portaled content.