🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

React Portals: Modals, Overlays, and Event Flow

React PatternsOverlaysđŸŸĸ Free Lesson

What You'll Learn

  • 1Explain why a modal rendered inside an overflow-hidden ancestor cannot escape it
  • 2Mount overlay content into a portal target without losing React event handling
  • 3Predict how click events propagate when the DOM parent differs from the React parent
  • 4Handle focus, the escape key, and background scroll for an accessible overlay

The overflow problem every modal eventually hits

A dialog is supposed to sit above the whole page. The DOM has other plans. Any ancestor with overflow set to hidden, with a transform, with a filter, or with a containing block created by perspective clips its descendants, and a modal that is a child of a scrolling sidebar renders inside that sidebar's box. The result looks correct in development on a wide screen and breaks the moment the dialog appears inside a collapsed panel.

Portals exist for exactly this. They let you render a subtree into a different DOM node while React keeps treating that subtree as a child of the component that declared it. The markup lands at the end of the body, outside every clipping ancestor, and your component code stays in the same place in the tree where the state and the handlers already live.

createPortal in practice

The API is one function: pass the children you want relocated and the DOM node that should receive them. Everything else, including context, event handling, and lifecycle, behaves as though nothing moved.

import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';

function Modal({ open, onClose, title, children }) {
  useEffect(() => {
    if (!open) return undefined;
    const onKey = (event) => {
      if (event.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  return createPortal(
    <div className="modal-backdrop" role="presentation" onClick={onClose}>
      <div
        className="modal-panel"
        role="dialog"
        aria-modal="true"
        aria-label={title}
        onClick={(event) => event.stopPropagation()}
      >
        <header className="modal-header">
          <h2>{title}</h2>
          <button type="button" aria-label="Close dialog" onClick={onClose}>×</button>
        </header>
        <div className="modal-body">{children}</div>
      </div>
    </div>,
    document.getElementById('modal-root')
  );
}

Two details in that fragment matter more than the plumbing. The dialog carries role and aria-modal so assistive technology knows a modal is open, and the backdrop handles the click that dismisses it while the panel stops propagation so clicks inside the dialog never fall through to the page behind.

Events bubble through the React tree

This is the part that surprises people. Portal children are appended to another DOM node, but React still dispatches events through the component tree, not through the DOM hierarchy. A click inside a portal bubbles to the React parent of the component that rendered it, even though no DOM ancestor connects them.

function Toolbar() {
  const [menuOpen, setMenuOpen] = useState(false);

  const handleClick = () => {
    console.log('toolbar clicked, menu open:', menuOpen);
  };

  return (
    <div className="toolbar" onClick={handleClick}>
      <button type="button" onClick={() => setMenuOpen((o) => !o)}>
        Actions
      </button>
      {menuOpen &&
        createPortal(
          <ul className="menu" role="menu">
            <li role="menuitem"><button type="button">Duplicate</button></li>
            <li role="menuitem"><button type="button">Archive</button></li>
          </ul>,
          document.getElementById('menu-root')
        )}
    </div>
  );
}

The menu lives at the end of the body, yet a click on Duplicate still reaches the toolbar's handler because the React parent chain is intact. That is usually what you want, since the menu is conceptually part of the toolbar. When you do not want it, stop propagation at the portal boundary or move the portal higher in the component tree so the offending handler is not an ancestor.

Choosing where the portal goes

The destination node is a design decision with consequences for stacking, theming, and testing. Most applications create a handful of fixed containers once at startup rather than looking one up on every render.

TargetStrengthsWatch out for
A single modal root appended to bodyOne stacking context, simple z-index storyAll dialogs share the root, so ordering must be managed
Separate roots per overlay typeMenus, tooltips, and dialogs stack predictablyMore nodes to create and keep in the document
A shadow DOM hostStyles cannot leak in or outEvent retargeting complicates detection of outside clicks
An element inside the layoutEasy to style with existing classesReintroduces the clipping problem portals exist to solve

Whatever you choose, render the containers in your document shell and look them up by id, with a guard that returns null during the first client render so server-rendered output matches.

Anchoring a floating element to its target

Moving the markup to the end of the body is only half the job, because a floating element has to be positioned relative to the element that opened it, and that element moves when the page scrolls or the window resizes. Two strategies are common, and the choice depends on how much layout the overlay needs.

Fixed positioning with coordinates computed from the trigger's bounding rectangle is the simplest. Measure on open, recompute on scroll and resize, and clamp the result to the viewport so the element never sits half off-screen. The measurement must happen after layout, which means a layout effect or a resize observer rather than a value captured during render. Reading a rectangle during render produces a number that is already stale by the time React commits.

The more robust option is a positioning library that implements flip and shift: flip the element to the opposite side of the trigger when the preferred side lacks room, and shift it along the axis to keep it inside the viewport. These libraries also handle the arrow offset, the scroll container that clips the calculation, and the virtual keyboard on mobile, all of which are individually small and collectively exhausting to reimplement.

Whichever you choose, remember that the floating element is in a portal, so its own ancestors no longer clip it, but the scroll container you measured may still be scrolling independently. Recompute when that container scrolls, not only when the window does.

Focus, the escape key, and background scroll

A modal that does not manage focus is a trap for keyboard users. Move focus into the dialog when it opens, keep it cycling within the panel while it is open, and return it to the trigger when it closes. The dialog element with the native showModal method does all of this for free, which is worth considering before building a custom one. If you keep the custom implementation, track the previously focused element in a ref, focus the first interactive element in the panel on mount, and restore focus in the cleanup.

Lock background scrolling at the same time by setting overflow hidden on the document element, and remember to restore the previous value rather than assuming it was visible. Padding equal to the scrollbar width avoids the layout jump when the scrollbar disappears.

Server rendering and timing

Portals require a DOM node, which does not exist during server rendering. Guard the lookup so the first client render matches the server output, then mount the portal content in an effect, or render nothing on the server and let the client hydrate the overlay. The alternative, rendering a different tree shape on each side, produces hydration warnings that are easy to misread as unrelated bugs.

Timing also matters for the portal target itself. Looking up an element during module evaluation runs before the document is ready in most setups, and looking it up on every render is wasted work. Resolve it once inside the component with a state initializer or an effect, and treat a missing container as a recoverable condition with a clear warning in development.

Common Mistakes

Rendering a modal as a normal child and discovering it is clipped by an overflow-hidden ancestor

Fix: Render it through a portal into a container near the end of the body

Assuming a portal click no longer reaches the React parent

Fix: Expect bubbling through the React tree and stop propagation at the portal boundary when needed

Querying the portal container on every render with no guard for the server

Fix: Guard the lookup and fall back to rendering nothing until the container exists

Opening a dialog without moving focus into it or returning focus on close

Fix: Store the previously focused element, focus on open, and restore focus in cleanup

Best Practices

  • Create a small number of stable portal containers once in the document shell
  • Always set role, aria-modal, and an accessible name on the dialog element
  • Close on escape and on backdrop click, and make the close button reachable by keyboard
  • Restore background scroll and focus when the overlay unmounts
  • Stop propagation at the portal boundary so page-level handlers do not fire unexpectedly

Key Takeaways

  • Clipping ancestors break modals; portals relocate the markup without relocating the component
  • React events bubble through the component tree, so portal children still reach their React parents
  • One or two fixed containers at the end of the body keep stacking contexts simple
  • Focus trapping, escape handling, and scroll locking are part of the feature, not polish
  • Portal targets must be guarded so server rendering and the first client render agree
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement