What You'll Learn
- 1Structure a small layer registry so overlays render into stable, predeclared containers
- 2Keep one z-index scale across the app instead of scattering arbitrary numbers
- 3Trap and restore focus correctly when one dialog opens another
- 4Lock background scroll without layout shift and without breaking nested overlays
A single modal is easy. The difficulty appears when a confirmation dialog opens from inside a settings drawer while a toast is already on screen, and each of those layers was written by someone who assumed it was the only one. z-index values start as reasonable numbers and become an arms race, scroll locking is applied and restored by two components that disagree about the previous value, and focus ends up trapped in a dialog that is no longer the topmost one. The fix is not a cleverer portal call. It is treating overlays as a managed stack with declared levels, one scroll lock owner, and a focus handoff protocol.
One root per layer, decided once
Portals solve clipping, but they do not solve ordering by themselves. If every overlay renders into a single container at the end of the body, stacking depends entirely on the order React happens to commit the nodes, which changes when one component unmounts earlier than expected. The stable approach is to declare a fixed set of containers in the document shell â background, overlay, modal, popover, toast â and have every overlay pick its container by level. Ordering then follows from the container, not from mount order, and a popover opened from a dialog lands above it by construction rather than by a lucky number.
The containers belong in the HTML document, not in the React tree. A container rendered by the provider is itself a descendant of whatever clipping ancestor surrounds the provider, which quietly reintroduces the bug portals exist to avoid. Look the elements up once, keep a null guard for the first render and for server rendering, and render nothing until they exist.
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
export const LEVELS = {
background: 100,
overlay: 200,
modal: 300,
popover: 400,
toast: 500,
};
const LayerContext = createContext({ push: () => () => {} });
export function LayerProvider({ children }) {
const [layers, setLayers] = useState([]);
const [ready, setReady] = useState(false);
useEffect(() => setReady(true), []);
const push = useCallback((node, level = 'modal') => {
const token = { id: Symbol('layer'), node, level };
setLayers((current) => [...current, token]);
return () => setLayers((current) => current.filter((item) => item.id !== token.id));
}, []);
const value = useMemo(() => ({ push }), [push]);
return (
<LayerContext.Provider value={value}>
{children}
{ready &&
layers.map((layer) => {
const container = document.getElementById('layer-' + layer.level);
return container ? createPortal(layer.node, container) : null;
})}
</LayerContext.Provider>
);
}
export function useOverlay() {
return useContext(LayerContext);
}
With this in place a component stops reasoning about stacking entirely. A toast pushes at the toast level, a drawer at the modal level, a menu inside the drawer at the popover level, and the DOM order of the four containers settles the rest. The id lookup runs only when layers change, which is rare enough that it costs nothing.
Focus trapping that hands off between nested dialogs
The naive focus trap queries the dialog for focusable elements once on mount and cycles Tab between the first and the last. It breaks the moment a second dialog opens on top, because both traps are listening and both believe they are active: the top dialog cycles focus while the underneath one yanks it back, and the user watches the caret teleport. Traps have to be a stack where only the top member handles key events, and each new trap must remember where focus came from so it can hand it back on the way out.
import { useEffect } from 'react';
const trapStack = [];
const SELECTOR = [
'button:not([disabled])',
'a[href]',
'input:not([disabled])',
'select:not([disabled])',
'textarea:not([disabled])',
'[tabindex]:not([tabindex="-1"])',
].join(',');
export function useFocusTrap(ref, active) {
useEffect(() => {
if (!active || !ref.current) return undefined;
const root = ref.current;
const previouslyFocused = document.activeElement;
const isTop = () => trapStack[trapStack.length - 1] === root;
trapStack.push(root);
const first = root.querySelector(SELECTOR);
if (first) first.focus();
const onKeyDown = (event) => {
if (event.key !== 'Tab' || !isTop()) return;
const focusable = [...root.querySelectorAll(SELECTOR)];
if (!focusable.length) return;
const firstItem = focusable[0];
const lastItem = focusable[focusable.length - 1];
if (event.shiftKey && document.activeElement === firstItem) {
event.preventDefault();
lastItem.focus();
} else if (!event.shiftKey && document.activeElement === lastItem) {
event.preventDefault();
firstItem.focus();
}
};
document.addEventListener('keydown', onKeyDown);
return () => {
document.removeEventListener('keydown', onKeyDown);
const index = trapStack.indexOf(root);
if (index >= 0) trapStack.splice(index, 1);
if (previouslyFocused && typeof previouslyFocused.focus === 'function') {
previouslyFocused.focus();
}
};
}, [ref, active]);
}
Two properties make this correct under nesting. The key handler bails out unless this trap is the top of the stack, so an underneath dialog never competes for Tab. And the cleanup restores focus to whatever was focused before that trap opened, which is exactly the element inside the parent dialog that the user was working in. Removing a trap in the wrong order is the classic bug: close the parent first and focus is restored to a node that no longer exists, so fall back to the document body when the previous target has been detached.
Scroll locking without the jump
Locking background scroll sounds trivial and produces three distinct bugs. Setting overflow hidden on documentElement removes the scrollbar and shifts the layout by its width, so the page jumps sideways the moment a modal opens. Recording the previous value per component means two overlays disagree when they unmount, and the second one restores a value that was already overwritten. And on iOS the document scrolls as a whole rather than an inner container, so locking the wrong element lets the page behind the dialog drift anyway.
The reliable pattern is a counter held by a single owner rather than a value held by each overlay. The first lock records the computed scrollbar width, adds padding of the same amount to the body to prevent the shift, and sets overflow to hidden. The last unlock reverses exactly what the first one did, with the counter guaranteeing that the intermediate overlays change nothing.
| Layer | Reserved range | Typical contents |
|---|---|---|
| Background | 0 to 99 | Decorative shapes, sticky headers |
| Overlay | 100 to 199 | Scrim behind a modal, drawer backdrop |
| Modal | 200 to 299 | Dialogs, drawers, full-screen sheets |
| Popover | 300 to 399 | Menus, tooltips, autocomplete, date pickers |
| Toast | 400 to 499 | Transient messages and undo bars |
Publish that table as design tokens and never write a raw z-index in a component. Raw numbers are how a menu ends up underneath a modal that was added two years later, and because a stacking context can hide a high number inside a low one, the failure looks like a rendering glitch rather than a missing layer. Also remember that transforms, filters and certain properties create a containing block; an element with a transform inside your dialog becomes the reference frame for fixed positioning, which is a separate and equally confusing symptom.
Events still belong to the React tree
Nested portals do not change event behaviour: React dispatches through the component tree, so a click inside a portal still bubbles to the React parent that rendered it. That is convenient for a menu that belongs to a toolbar and disastrous for a dialog rendered inside a form, where a submit or click handler fires twice â once through the React chain and once through the DOM. Stop propagation at the boundary of overlays that sit inside interactive ancestors, and prefer rendering the overlay from the state owner rather than from the field that triggers it when the handler is expensive.
Escape handling has the same nesting problem as focus. Every open dialog listens for the key, so a single Escape closes the drawer and the confirmation that lived inside it. Resolve it the same way: only the top layer of the stack responds, which falls out naturally if the key handler checks the same stack the focus trap uses.
Server rendering and the first client render
Portals need a container that does not exist during server rendering, and a document that is not there either. The guard in the provider handles that, but the component must still render the same shape on both sides, otherwise hydration complains about mismatched markup and React discards the server output. Two common resolutions: render the overlay content in the tree as a hidden node on the server and let the client move it into the portal after mount, or render nothing on the server and mount the overlay only in an effect, accepting that a dialog opened from an initial URL parameter appears a frame later.
Also defer the lookup itself. Reading getElementById during module evaluation runs before the body exists in most setups, and querying on every render is wasted work for something that changes only when a layer opens or closes.
Ephemeral layers deserve their own contract
Toasts and tooltips live at the top of the scale and behave differently from dialogs: they do not trap focus, they dismiss on a timer, and they must never steal the caret from someone typing. That means their containers should carry pointer-events none at the container level with pointer-events auto on the toast itself, so a gap between toasts does not swallow clicks meant for the page underneath. It also means announcements for assistive technology go through a polite live region rather than through focus movement, because moving focus to a transient message interrupts the user's task for something that will disappear in four seconds.
Common Mistakes
Giving every overlay its own z-index number chosen to beat the current largest
Fix: Publish one scale of reserved ranges and pick a level from it
Letting each dialog lock and unlock background scroll with its own recorded value
Fix: Route locking through one owner that counts locks and reverses only the first and last
Running a focus trap in every open dialog simultaneously
Fix: Keep a stack and let only the top trap respond to key events
Rendering portal containers inside the React tree where a clipping ancestor can catch them
Fix: Declare containers in the document shell and resolve them behind a null guard
Best Practices
- One container per level, declared in the document shell and looked up lazily
- Restore focus to the opener on unmount and fall back to body if it was detached
- Match Escape and click-outside handling to the top layer only
- Reserve padding for the scrollbar width so locking never shifts the layout
- Announce transient messages through live regions instead of moving focus
Key Takeaways
- Ordering should come from which container receives a portal, not from mount order or arbitrary numbers
- Focus traps and escape handling both need a stack so only the topmost overlay reacts
- Scroll locking must be refcounted by a single owner to survive overlapping overlays
- z-index is a system: publish ranges as tokens and never write a raw value in a component
- Server rendering needs a null guard and matching markup on both sides of hydration