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(children, domNode) renders children into domNode — here, directly into <body> — instead of inside the parent component’s DOM.
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'));}
Modal dialogs with
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,
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:
Whether you use <dialog>, a library or your own component, a modal must:
Have a label — aria-labelledby pointing at its heading (or aria-label).
Move focus inside when it opens — to the first sensible control, or the safest action for destructive dialogs (“Cancel” before “Delete”).
Keep focus inside while open, and make the rest of the page inert.
Close with Escape, and usually with a visible close button.
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}