Portals and modals

Topic 2 of 5 in Production patterns7 min readIntermediateFree course

Overview

Some UI needs to visually “break out” of where it lives in the component tree: a modal dialog over the whole page, a dropdown that extends beyond a scrolling container, a toast in the corner. If you render them inside a card with overflow: hidden or a low z-index, they get clipped or hidden behind other content. Portals let a component render its output somewhere else in the DOM.

createPortal

JSX
import { createPortal } from 'react-dom';

function Tooltip({ text, anchorRect }) {
  return createPortal(
    <div className="tooltip" style={{ top: anchorRect.bottom + 8, left: anchorRect.left }}>
      {text}
    </div>,
    document.body
  );
}

createPortal(children, domNode) renders children into domNode — here, directly into <body> — instead of inside the parent component’s DOM.

In the React tree, App contains CourseCard, which contains Modal (a portal). In the DOM, the body contains the root div, which contains an article with overflow hidden, and — separately, directly in the body — a div with role dialog. createPortal(…, document.body) places the modal there. It escapes overflow and z-index problems in the DOM but still behaves as a child in React: it reads context and its events bubble to CourseCard.

Still part of the React tree

Even though the DOM nodes live elsewhere, the portal’s content is still a child in React:

  • it receives props and can read context from its React ancestors (theme, auth, router),
  • its events bubble up the React tree: a click inside the portal triggers onClick handlers on React parents, even though they aren’t DOM ancestors,
  • it’s unmounted when its React parent unmounts.

That makes portals feel completely natural to use — you write <Modal> inside the component that owns its state.

A reusable portal target

Many apps add a dedicated container to index.html for overlays:

HTML
<div id="root"></div>
<div id="overlays"></div>
JSX
export function Overlay({ children }) {
  return createPortal(children, document.getElementById('overlays'));
}

Building an accessible modal from scratch is surprisingly hard: you need to trap focus inside, make the rest of the page inert, close on Escape, restore focus afterwards, and layer it above everything. The native HTML <dialog> element does all of this when opened with showModal():

JSX
import { useEffect, useId, useRef } from 'react';

export function Modal({ open, onClose, title, children }) {
  const ref = useRef(null);
  const titleId = useId();

  useEffect(() => {
    const dialog = ref.current;
    if (open && !dialog.open) dialog.showModal();
    if (!open && dialog.open) dialog.close();
  }, [open]);

  return (
    <dialog
      ref={ref}
      aria-labelledby={titleId}
      onCancel={(e) => {
        e.preventDefault();   // Escape: let React state close it
        onClose();
      }}
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();   // click on the backdrop
      }}
    >
      <h2 id={titleId}>{title}</h2>
      {children}
      <button onClick={onClose}>Close</button>
    </dialog>
  );
}

With showModal(), the browser:

  • places the dialog in the top layer, above every z-index — no portal needed,
  • makes the rest of the page inert (not clickable or focusable),
  • moves focus into the dialog, and returns it to the previously focused element when it closes,
  • fires a cancel event when the user presses Escape,
  • shows a ::backdrop you can style.
CSS
dialog::backdrop { background: rgb(0 0 0 / 0.4); }
dialog { border: none; border-radius: 12px; padding: 24px; max-width: 32rem; }

The effect here is a legitimate one: it synchronises React state (open) with an external system — the browser’s dialog API.

Testing tip: jsdom, the simulated DOM used by Vitest and Testing Library, doesn’t implement showModal() or close(). Stub them in your test setup so dialog components can be tested:

JavaScript
HTMLDialogElement.prototype.showModal = vi.fn(function () { this.setAttribute('open', ''); });
HTMLDialogElement.prototype.close = vi.fn(function () { this.removeAttribute('open'); });

Focus trapping and the top layer can only be checked in a real browser — a job for Playwright.

Controlled by state

Keep the “is it open?” state in the parent, like any other UI state:

JSX
function CourseActions({ course }) {
  const [isSharing, setIsSharing] = useState(false);

  return (
    <>
      <button onClick={() => setIsSharing(true)}>Share</button>
      <Modal open={isSharing} onClose={() => setIsSharing(false)} title={`Share ${course.title}`}>
        <ShareLinks course={course} />
      </Modal>
    </>
  );
}

Accessibility checklist for overlays

Whether you use <dialog>, a library or your own component, a modal must:

  1. Have a label — aria-labelledby pointing at its heading (or aria-label).
  2. Move focus inside when it opens — to the first sensible control, or the safest action for destructive dialogs (“Cancel” before “Delete”).
  3. Keep focus inside while open, and make the rest of the page inert.
  4. Close with Escape, and usually with a visible close button.
  5. Return focus to the element that opened it.

useId() generates a unique, stable id for connecting labels and descriptions — safe even when the component appears many times and with server rendering.

Other overlays

  • Toasts and notifications — portal into a fixed container; announce them to screen readers with role="status" (polite) or role="alert" (urgent).
  • Dropdowns, popovers and tooltips — positioning relative to an anchor is fiddly (flipping at screen edges, scrolling). The browser’s Popover API (popover attribute) handles top-layer display and light dismiss; libraries like Floating UI handle positioning.
  • Component libraries — Radix UI, React Aria and shadcn/ui provide accessible, unstyled dialogs, menus and popovers that handle every edge case. For complex widgets, using one is usually wiser than building your own.

Prefer the platform: <dialog>, popover and inert now solve problems that used to need hundreds of lines of JavaScript. Reach for a portal when you need to render elsewhere for other reasons — like a toast container or rendering into a non-React page.

Exercise

An accessible confirm dialog

Build a ConfirmDialog({ open, title, children, onConfirm, onCancel }) using the native <dialog> element: call showModal() when open becomes true and close() when it becomes false (in an effect using a ref). Label the dialog with its title via aria-labelledby (use useId), handle the Escape key by calling onCancel through the dialog’s cancel event, and put the Cancel button first so it receives focus. Use it from a DeleteCourseButton that asks “Delete this course?” before calling onDelete.

JavaScript
import { useEffect, useId, useRef, useState } from 'react';

export function ConfirmDialog({ open, title, children, onConfirm, onCancel }) {
  // your code here
}

export function DeleteCourseButton({ onDelete }) {
  // your code here
}

Summary

  • createPortal(children, domNode) renders children into a different DOM node while keeping them in the React tree.
  • Portals escape overflow: hidden and z-index stacking problems for modals, tooltips and toasts.
  • Portal content still reads context, and its events bubble to its React parents, not its DOM parents.
  • The native <dialog> element with showModal() gives you a top layer, focus trapping, Escape and inertness for free.
  • Accessible modals need a label, focus management, Escape to close and focus returned to the trigger.