Performance & Patterns
React Portals
createPortal renders children into a different DOM node while keeping them in the same React tree. Events still bubble to the React parent, and context still flows down, even though the DOM position is elsewhere.
What is Portals in React?
createPortal renders children into a different DOM node while keeping them in the same React tree. Events still bubble to the React parent, and context still flows down, even though the DOM position is elsewhere.
Why Portals matters
Modals, tooltips and dropdowns break when an ancestor has overflow: hidden, a transform, or a low z-index. A portal escapes that stacking context without moving the component in your code.
Portals example
import { createPortal } from 'react-dom';
function Modal({ open, onClose, children }) {
if (!open) return null;
return createPortal(
<div className="overlay" onClick={onClose}>
<div className="modal" onClick={e => e.stopPropagation()}>{children}</div>
</div>,
document.body
);
}How this works
The overlay becomes a direct child of body, so no ancestor’s overflow or transform can clip it. stopPropagation on the inner div stops a click inside the modal from closing it.
Key points to remember
- Events bubble through the React tree, not the DOM tree — usually what you want.
- Add role="dialog", aria-modal and focus trapping for accessibility.
- Guard document access if the component is server-rendered.
Common mistakes with Portals
- Referencing document during server rendering, which throws.
- Forgetting to restore focus and scroll position when the modal closes.
React Portals— Interview Questions & FAQs
Why does my modal get cut off by a parent element?+
An ancestor has overflow: hidden or a transform that creates a stacking context. Render the modal through a portal into document.body so no ancestor can clip it.
