Rendering and data flow

Render an overlay with a portal

Place a component child in another DOM container while keeping it in the same React component tree.

A portal renders children into another DOM node while keeping them in the same React tree.

import { createPortal } from 'react-dom'

function Modal({ children }) {
  const modalRoot = document.getElementById('modal-root')
  return createPortal(children, modalRoot)
}

This is useful when an overlay must escape a container’s clipping or stacking context. The modal DOM can live near the end of body while its component remains a child of the page in React.

Context still follows the React tree. React events also propagate through React parents, not only DOM parents.

A portal only changes placement. It does not create accessible dialog behavior.

A modal still needs an accessible name, focus moved inside, Escape and close-button handling, background interaction rules, and focus returned to the opener.

Use the native dialog element where it fits; it provides useful browser behavior that a generic portal does not.

Inspect the component tree and DOM tree for a portal. Confirm the same content has different parents in the two views.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →