React Portals
Normally a component's output is inserted inside its parent's DOM node. A portal lets a component render its children into a different place in the DOM — typically document.body — while staying a normal part of the React tree. Portals are the standard tool for modals, tooltips, toasts and dropdowns that must escape a parent's overflow: hidden or z-index stacking.
import { createPortal } from 'react-dom';
createPortal(children, domNode)Note:
createPortalis exported fromreact-dom(notreact-dom/client).
Why portals?
Here a modal is rendered inside a small card with overflow: hidden. Without a portal it gets clipped; with a portal it covers the page as intended:
import { useState } from 'react';
import { createPortal } from 'react-dom';
function Modal({ children, onClose }) {
return (
<div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.45)', display: 'grid', placeItems: 'center', zIndex: 10 }} onClick={onClose}>
<div style={{ background: 'white', padding: 20, borderRadius: 10, minWidth: 240 }} onClick={(e) => e.stopPropagation()}>
{children}
<p><button onClick={onClose}>Close</button></p>
</div>
</div>
);
}
export default function App() {
const [mode, setMode] = useState(null);
return (
<div style={{ width: 260, height: 110, overflow: 'hidden', border: '2px solid #888', borderRadius: 8, padding: 8, position: 'relative', transform: 'translateZ(0)' }}>
<strong>Small card (overflow: hidden)</strong>
<p>
<button onClick={() => setMode('inline')}>Open inline</button>{' '}
<button onClick={() => setMode('portal')}>Open with portal</button>
</p>
{mode === 'inline' && <Modal onClose={() => setMode(null)}>😖 I'm clipped by my parent.</Modal>}
{mode === 'portal' && createPortal(<Modal onClose={() => setMode(null)}>🎉 I'm rendered into document.body!</Modal>, document.body)}
</div>
);
}The card's transform creates a new containing block, so even position: fixed gets trapped inside it — a common real-world situation. The portal escapes because its DOM lives directly under <body>.
Portals stay in the React tree
Even though the DOM node is elsewhere, the portal's content behaves like a normal child in React:
- It receives context from its React parents.
- Its events bubble to React ancestors, following the React tree rather than the DOM tree.
import { createContext, useContext, useState } from 'react';
import { createPortal } from 'react-dom';
const UserContext = createContext('nobody');
function Toast({ message }) {
const user = useContext(UserContext);
return createPortal(
<div style={{ position: 'fixed', bottom: 16, right: 16, background: '#323232', color: 'white', padding: '10px 16px', borderRadius: 8 }}>
{message} — signed in as <strong>{user}</strong>{' '}
<button>OK</button>
</div>,
document.body
);
}
export default function App() {
const [clicks, setClicks] = useState(0);
const [show, setShow] = useState(true);
return (
<UserContext value="mai@example.com">
<div onClick={() => setClicks(clicks + 1)} style={{ border: '1px dashed #999', padding: 10, width: 280 }}>
<p>Clicks bubbled to this div: {clicks}</p>
<button onClick={() => setShow(!show)}>{show ? 'Hide' : 'Show'} toast</button>
{show && <Toast message="Settings saved" />}
</div>
</UserContext>
);
}Click the toast's OK button in the corner: the counter in the dashed box increases, although the toast's DOM is not inside that box. The toast also reads the user from context.
A tooltip that escapes scroll containers
Tooltips are measured relative to the trigger and drawn at body level so that scrolling panels can't cut them off:
import { useRef, useState } from 'react';
import { createPortal } from 'react-dom';
function Tooltip({ text, children }) {
const ref = useRef(null);
const [pos, setPos] = useState(null);
function show() {
const r = ref.current.getBoundingClientRect();
setPos({ left: r.left + r.width / 2, top: r.top - 8 });
}
return (
<>
<span ref={ref} onMouseEnter={show} onMouseLeave={() => setPos(null)} style={{ borderBottom: '1px dotted', cursor: 'help' }}>
{children}
</span>
{pos && createPortal(
<div style={{ position: 'fixed', left: pos.left, top: pos.top, transform: 'translate(-50%, -100%)', background: '#222', color: '#fff', padding: '4px 8px', borderRadius: 4, fontSize: 13, whiteSpace: 'nowrap' }}>
{text}
</div>,
document.body
)}
</>
);
}
export default function App() {
return (
<div style={{ height: 90, width: 280, overflow: 'auto', border: '1px solid #ccc', padding: 8, marginTop: 40 }}>
<p>Hover over <Tooltip text="A JavaScript library for UIs">React</Tooltip> or <Tooltip text="HTML-like syntax in JS">JSX</Tooltip>.</p>
<p>This box scrolls, but the tooltips are never clipped.</p>
<p>More text…</p>
</div>
);
}Accessibility checklist for modals
Portals solve the rendering problem; good modals also need:
| Need | How |
|---|---|
| Announce as a dialog | role="dialog" and aria-modal="true", plus aria-labelledby |
| Move focus into the modal | focus the first button in an effect |
| Close with Escape | keydown listener for 'Escape' |
| Return focus on close | remember document.activeElement and restore it |
| Block the background | the native <dialog> element with showModal() handles much of this for you |
Tip: For many cases, the built-in HTML
<dialog>element plus a ref (dialogRef.current.showModal()) is simpler than a hand-made portal modal, because the browser puts it in the top layer automatically.
Test yourself
What does createPortal(children, document.body) do?
- Copies the component to a new window
- Renders children into document.body while keeping them in the React tree
- Removes the component from React
- Creates a new React root
A click inside a portal — where does it bubble in React?
- Only through DOM ancestors of the portal node
- Through its React ancestors, as if it were rendered in place
- Nowhere; portal events don't bubble
- Only to document.body
Which is a typical use case for portals?
- Fetching data
- Modals and tooltips that must escape overflow or z-index constraints
- Defining routes
- Memoizing components