React Portals and z-index Layering (Legacy Pattern)
createPortal(..., document.body) escaped local CSS Stacking Context traps by teleporting DOM nodes to <body>. With the Browser Top Layer now universal, Native Dialog and Popover API supersede manual portals.
createPortal + z-index Hack vs Native Top Layer
createPortal(
<div className="fixed inset-0 z-[9999]">
<FocusTrap><Modal /></FocusTrap>
</div>,
document.body
);Requires manual Escape key, focus trap, inert siblings, and z-index coordination.
<dialog ref={ref} onCancel={onClose}>
<ModalContent />
</dialog>
// ref.current.showModal() promotes to Top LayerAutomatic Top Layer, ::backdrop, Escape dismiss, and background inertness.
Under the Hood
Picture mailing your furniture to a neighbor's rooftop just so it sits higher than your ceiling: createPortal relocates the DOM node to document.body, yet still leaves you wiring Escape keys, focus traps, and z-index treaties with every other tenant.
- DOM Reparenting:
createPortalkeeps React's synthetic event bubbling intact while mounting the real DOM subtree underdocument.body. - Global
z-indexCollisions: Portals still compete inside the root stacking context (z-50vsz-[9999]). - Manual A11y: Without
<dialog>.showModal(), JS must trap Tab focus, lock body scroll, and restore focus on close.
// Superseded: portal + hardcoded z-index
createPortal(<div className="fixed inset-0 z-[9999]">{children}</div>, document.body);
// Modern replacement: stays inline in component DOM, renders in Top Layer
<dialog ref={dialogRef} className="backdrop:bg-black/50">{children}</dialog>Problem Genealogy
- 2017 (
ReactDOM.createPortal): Solvedoverflow: hiddenclipping in nested component trees. - 2018–2023 (Overlay Library Stack): Spawned
react-focus-lock,body-scroll-lock, and Floating UIz-indexmanagers. - 2024 (Top Layer Baseline):
<dialog>and[popover]made DOM teleportation unnecessary for modals and menus.
Production Pitfalls
- Inherited CSS Breakage: Teleporting a component to
document.bodydetaches it from local CSS custom properties and container queries. - Broken Screen-Reader Containment: Forgetting
aria-modalorinerton siblings lets keyboard users tab behind the backdrop.
- When not to use
createPortal: Never reach forcreatePortalfor new modals, drawers, or tooltips, use<dialog>.showModal()or[popover]instead.
Connections & Logical Next Steps
Portals only exist to escape local ancestor stacking contexts and overflow clipping.
Native Top Layer promotion eliminates the need to teleport DOM nodes to document.body.
Native showModal() replaces React createPortal and z-index hacks with engine-managed Top Layer and inert.
Declarative HTML attribute rendering menus, tooltips, or toasts in the Top Layer with automatic light-dismiss and zero JavaScript.