Sub topic 3
Rendering with createPortal
This chapter assumes you know function components, JSX, props and children, and the useState and useEffect hooks. It also assumes you know that the DOM is a tree of nodes with document.body at the top. The previous chapters covered why clipped and buried UI happens and how the React tree differs from the DOM tree. Here you use the API that fixes it.
The API
createPortal comes from react-dom, not from react.
createPortal(children, domNode, key?)childrenis anything React can render: JSX, strings, or fragments.domNodeis a real DOM element that already exists. React appends the rendered output inside it.keyis optional. You rarely need it.
The call returns a React node. You return that node from a component like any other JSX. The call does not move anything by itself. It only tells React where in the DOM the output goes.
A first example
This toast sits inside a parent with overflow: hidden. Without a portal, the parent would clip it.
import { createPortal } from 'react-dom';
function Toast({ message }) {
return createPortal(
<div
role="status"
style={{
position: 'fixed',
bottom: 16,
right: 16,
padding: '8px 12px',
background: '#222',
color: '#fff',
}}
>
{message}
</div>,
document.body
);
}
export default function App() {
return (
<div style={{ overflow: 'hidden', height: 80, border: '1px solid #999' }}>
<p>Card content</p>
<Toast message="Saved" />
</div>
);
}In the browser's element inspector, the <p> is inside the bordered div. The toast div is a direct child of <body>. The bordered parent's overflow no longer affects it, because the parent is no longer an ancestor in the DOM.
Two trees, one component
The component that calls createPortal stays where you wrote it in the React tree. Only the DOM output moves.
Because the component stays in the React tree, it keeps its place in React's own bookkeeping. It receives context from its React ancestors. State updates and re-renders follow the usual rules. Unmounting Toast removes its DOM node from body. Later chapters cover events and context in detail.
Updating and removing portal content
Portal content re-renders when props or state change, like any component. To show it conditionally, wrap the call in a condition:
import { useState } from 'react';
import { createPortal } from 'react-dom';
function Demo() {
const [open, setOpen] = useState(false);
return (
<div style={{ overflow: 'hidden' }}>
<button onClick={() => setOpen((v) => !v)}>Toggle</button>
{open &&
createPortal(
<p style={{ position: 'fixed', top: 8, left: 8 }}>Hello from body</p>,
document.body
)}
</div>
);
}When open becomes false, React removes the paragraph from body. You do not clean up the DOM yourself.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| "Target container is not a DOM element" | `domNode` is `null`, for example `getElementById` found nothing | Make sure the element exists before rendering, or fall back to `document.body` |
| `document is not defined` | The component runs on the server | Look up the container inside an effect, covered in the server rendering chapter |
| Content appears but is not positioned | The portal escapes the parent, but your CSS still depends on it | Use `position: fixed` or `absolute` with explicit coordinates |
| Content is still hidden behind other UI | Another element has a higher `z-index` in the root stacking context | Raise the portal element's `z-index` or render it last in `body` |
Rules to remember
- Pass a real DOM node. Do not pass a React element or a ref object. If you use a ref, pass
ref.current, and only after the ref is set. - Do not render into a node that React itself manages, such as the root container, or into a node whose children you also edit by hand.
- Style portal content for its new DOM location. Selectors such as
.card .toastno longer match, because the toast is not inside.cardin the DOM.
Exercise
A component calls createPortal(<span>Hi</span>, document.getElementById('missing')) and no element with that id exists. What happens, and how would you make the component safe?
Show answer
React throws "Target container is not a DOM element" because getElementById returns null. Make it safe by checking that the container exists before calling createPortal, for example by returning null when it is missing, or by falling back to document.body.