React · Chapter 28 of 42

Portals

Portals let you render a child component into a DOM node that exists outside the parent component's DOM hierarchy — useful for modals, tooltips, and dropdowns that need to escape parent overflow/z-index constraints.

Even though the DOM node is elsewhere, the portal content still behaves like a normal React child for events and context.

Creating a portal

Use `ReactDOM.createPortal(child, domNode)` where `domNode` is typically a separate element like `#modal-root` in your HTML.

Why use portals

Modals often need to render above all other content, unaffected by a parent's CSS `overflow: hidden` or `z-index` stacking context.

Example 1 (jsx)
import { createPortal } from "react-dom";

function Modal({ children }) {
  return createPortal(
    <div className="modal">{children}</div>,
    document.getElementById("modal-root")
  );
}
Output
(renders the modal into #modal-root, outside the app's div)

The modal content appears in a different DOM node than the parent component.

Key points

  • Portals render children into a DOM node outside the parent hierarchy.
  • Created with ReactDOM.createPortal(child, domNode).
  • Commonly used for modals, tooltips, and popovers.
  • Events still bubble through React's tree, not the actual DOM tree.
💡 Note: You need a dedicated DOM node (e.g. `<div id="modal-root">`) in your index.html for portals to target.

📝 Quick Quiz

1. What function creates a portal?

2. What is a common use case for portals?

3. Do events from portal content bubble through the React tree?