Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 132 ยท Advanced Patterns

Portals and Overlays

Learn React portals with createPortal - render modals and tooltips outside clipped parents, understand event bubbling through portals, trap focus, close on Escape and handle z-index and accessibility.

Most of the time, where a component sits in the React tree is also where its DOM nodes sit in the page. That is usually what you want, but not for overlays. A modal dialog, a dropdown menu, a tooltip or a toast has to appear on top of everything else. If it is rendered deep inside a card with overflow: hidden, a transformed container or a low z-index, the browser clips it or paints it underneath other things, however clever your CSS is.

Portals solve this. A portal lets a component render its children into a different place in the DOM while keeping them in the same place in the React tree. This lesson explains how createPortal works, the surprising (and useful) rule about events and context, and then builds the parts of a real overlay: Escape to close, focus handling, a tooltip and an accessible modal.

The problem portals solve

Here is a tooltip-like popup rendered the normal way inside a box that clips its content. Run it and read the result.

An overlay clipped by its parent

The yellow popup is cut off at the bottom of the blue box. No amount of z-index fixes this: overflow: hidden clips descendants, and position: absolute descendants are still descendants. The popup must live somewhere else in the DOM.

createPortal in one minute

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

createPortal(children, domNode, key?)

createPortal returns a React node. Whatever you pass as children is rendered inside domNode (any real DOM element, commonly document.body) instead of inside the parent component's DOM element. The call lives in import { createPortal } from 'react-dom', not react-dom/client.

Escaping the clipped parent with a portal

Click "Show popup": the yellow box now appears in full, outside the blue border, and the console prints the tag name of its DOM parent. Inspect the page and you would find it as a direct child of <body>, not inside the box. React did not move anything by hand; during the commit phase it simply attached the portal's DOM nodes to document.body.

What stays the same

A portal changes only the DOM parent. In the React tree the popup is still a child of the component that rendered it. That has important consequences:

  • State and props work normally. The portal content can read the parent's variables in closures and re-renders with it.
  • Context passes through. A portal inside <ThemeContext value="dark"> sees "dark", even though its DOM nodes sit elsewhere.
  • Unmounting follows the React tree. If the parent unmounts, the portal content is removed with it, and its effect cleanups run.
  • Events bubble through the React tree. This one surprises people, so it gets its own section.

Events bubble through portals

A native click on a DOM node bubbles up through its DOM ancestors. React's synthetic events instead bubble up through the React ancestors. For a normal tree the two are the same. For a portal they differ: a click inside the portal travels up to the component that rendered it, as if the portal were an ordinary child, even though the DOM says otherwise.

Clicks bubble through the React tree

Click the button: the console prints 1. button inside the portal and then 2. parent div in the React tree. The <div onClick> fires although the button is not a DOM descendant of it.

This is deliberate and usually helpful. A reusable <Modal> can sit inside any component, and a click inside the modal behaves as if it were a child, so existing patterns such as "close when the user clicks outside this component" or form onSubmit handlers keep working. It also causes classic bugs:

  • A modal inside a clickable card: clicking the modal's "Save" button also triggers the card's onClick. Fix with event.stopPropagation() in the modal, or check event.target/event.currentTarget.contains(event.target) in the card's handler.
  • A modal with its own <form> rendered (in the React tree) inside another form: the inner form's submit event bubbles to the outer form's onSubmit handler, so both run. Check event.target or stop propagation in the inner handler.

Native listeners are different: document.addEventListener('click', ...) follows the DOM, so a click in a portal in <body> is outside your component's DOM node. Click-outside hooks that use ref.current.contains(event.target) therefore treat portal content as "outside"; handle that explicitly if your dropdown opens a portal menu.

Building a modal step by step

A usable modal needs more than a portal. Here are the requirements for a trustworthy one:

  1. Render into document.body so no ancestor can clip it.
  2. A backdrop that blocks interaction behind it and closes the modal on click (carefully: only for clicks on the backdrop itself).
  3. Escape closes it.
  4. Focus moves into the dialog when it opens, stays inside while it is open (a focus trap), and returns to the element that opened it when it closes.
  5. Correct semantics: role="dialog", aria-modal="true", and a label (aria-labelledby).
A modal with Escape and backdrop click

Open it and press Escape: the modal closes and the console prints closing with Escape. Clicking on the dark area prints closing from the backdrop, but clicking inside the white dialog does not close it, because event.target === event.currentTarget is only true when the backdrop itself was the clicked element.

Notice the effect: it adds a document listener on setup and removes it on cleanup, and it depends on onClose. Because App passes a new arrow function on every render, the effect re-subscribes each time App renders while the modal is open; that is correct and cheap, but if it bothers you, read the latest handler through useEffectEvent.

Focus: the part most modals get wrong

The modal above is visually right but fails keyboard and screen-reader users: after opening, focus is still on the "Open settings" button behind the backdrop, Tab walks through the page underneath, and after closing, focus is lost. A dialog must:

  • Move focus in when it opens, usually to the first focusable element or the dialog container itself (tabIndex={-1}).
  • Trap Tab so that Tab on the last control wraps to the first, and Shift+Tab does the reverse.
  • Restore focus to the trigger when it closes.
Focus moves in, is trapped, and is restored

Open it with the keyboard (focus the Subscribe button, press Enter) and the email field already has focus. Tab through Send and Cancel, then Tab once more: focus wraps back to the email field instead of escaping into the page. Press Escape, and focus returns to Subscribe. The cleanup function of the mount effect is what restores focus: it runs when the modal unmounts, whatever the reason (Send, Cancel, Escape).

Real-world dialogs often use the native <dialog> element with showModal(), which gives you the top layer, the backdrop, the focus trap and Escape handling for free, no portal needed. Use it when your browser support allows, and keep the portal approach for custom overlays that need to live outside the DOM tree (toasts, menus, tooltips) or where <dialog> is not a good fit. Also consider the inert attribute on the rest of the page to block interaction behind a modal.

A tooltip that positions itself

Tooltips, dropdown menus and popovers need coordinates. The trick is to measure the trigger with getBoundingClientRect(), then position a portaled position: fixed element. Measure in an event handler (or an effect), never in render; the render phase should not read the DOM.

A portal tooltip positioned from the trigger

Focus the word "portal" (Tab) or hover it: the dark tooltip appears under the word and is not clipped by the box, although the box has overflow: hidden and a small height. The tooltip responds to focus as well as hover, so keyboard users get it too. For production, a positioning library (Floating UI, for example) also handles flipping near viewport edges, scrolling and resizing, which this demo ignores.

Stacking contexts and z-index

If you used z-index: 9999 and it still doesn't work, the cause is almost always a stacking context. Elements with position + z-index, transform, opacity < 1, filter and several other properties start a new context, and z-index values only compete inside the same context. A modal with z-index: 9999 inside a transformed card cannot rise above a sibling of that card.

A portal into document.body fixes it because the overlay's context is then a top-level one, and you only need to compare it to other top-level layers. Practical rules:

  • Portal overlays to a root-level container, not into a random nested element.
  • Keep a short, named scale of z-index values (content, sticky header, dropdown, modal, toast) in CSS variables rather than magic numbers.
  • Be consistent about where overlays attach. If every portal goes into document.body in render order, later overlays naturally stack above earlier ones.
  • Many apps create a dedicated <div id="overlays"> after the app root and portal into that, which makes styling and testing easier.

Pitfalls and guidelines

  • Server rendering: document.body does not exist on the server. Render portals only after mount (useEffect + state, or only when isOpen is true after an interaction), or you will crash during SSR. See Server-Side Rendering and Hydration.
  • Portal targets must exist. createPortal(child, null) throws. If you portal into a custom container, create it before the first render, or guard with state.
  • Accessibility is not automatic. A portal is a DOM-location tool only. Dialog semantics, focus, labelling and keyboard handling are still your job (or your component library's). See Accessibility in React.
  • Don't hide the page's scroll by accident. Many modals add overflow: hidden to the body; remember to undo it in the cleanup, or the page will stay locked.
  • Styles don't follow the DOM. CSS selectors based on DOM ancestry (.card .popup) no longer match a portaled child. Style with classes on the portaled element itself.
  • Multiple roots: portals work across createRoot boundaries too; the React tree stays connected through the portal, which is how a component can render a widget into another part of the page.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does createPortal(children, document.body) change?

    A portal only changes the DOM parent. State, props, context and unmounting still follow the component that rendered the portal.
  2. 2. A button inside a portal is clicked. Which handlers run?

    React synthetic events bubble through the React tree, so a parent component's onClick sees clicks from inside a portal. Native document listeners follow the DOM instead.
  3. 3. Why does an overlay with z-index: 9999 sometimes still appear under another element?

    Properties such as transform, opacity below 1 and position with z-index create stacking contexts. Rendering the overlay in a portal at the body level avoids the trap.
  4. 4. Which is NOT part of a trustworthy modal dialog?

    A modal must keep keyboard focus inside it while open. Focusing the page behind it defeats the point of a modal and confuses screen reader users.
  5. 5. Why should you avoid calling createPortal(..., document.body) unconditionally during server rendering?

    There is no DOM on the server, so referencing document.body would throw. Render portals only after mount or after an interaction.

Summary

  • createPortal(children, domNode) renders children into another DOM node while keeping them in the same React tree position.
  • Use portals for modals, tooltips, menus and toasts that must escape clipping (overflow), stacking contexts or transforms.
  • State, props and context work through portals, and synthetic events bubble to React ancestors, not DOM ancestors.
  • A good modal closes on Escape and backdrop click, moves focus in, traps Tab, restores focus on close and exposes role="dialog" and aria-modal.
  • Position tooltips from getBoundingClientRect() measured in handlers or effects, not during render.
  • Guard portals for server rendering, avoid CSS that depends on DOM ancestry, and consider the native <dialog> element.

Next: Refs, forwardRef History and useImperativeHandle