Sub topic 4
Choosing a portal container
This chapter assumes you know function components, props and children, useState and useEffect, and the basics of the DOM and CSS stacking. You have already seen createPortal(children, container). Here you decide what container should be, and how to manage it safely.
What the container is
The second argument to createPortal is any real DOM node. React appends the portal's rendered output to that node. React does not create the node for you, and it does not clean it up. You own its lifecycle.
You have three common choices.
| Choice | How you get it | Good for | Main risk |
|---|---|---|---|
| `document.body` | Global, always exists in the browser | Quick modals and simple overlays | Many portals end up as unordered siblings of your app root |
| A dedicated `#portal-root` | A `<div>` you add to `index.html` | Most apps with several overlays | Must exist before the portal renders |
| A node you create in code | `document.createElement` inside an effect | Libraries, isolated overlays | You must remove it on cleanup |
Option 1: document.body
This is the shortest path and works well for a single modal. The earlier modal example uses it. The downside is that every portal appends directly to body, next to your app root. Global CSS such as body > * rules can then hit overlays by accident, and tools that mark the app root as inert will not affect them.
Option 2: a dedicated container
Add a sibling of your app root in the HTML file:
<body>
<div id="root"></div>
<div id="portal-root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>Overlays now live in one predictable place. You can style, inspect and hide that node as a group. Because #portal-root comes after #root in the document, it also paints above the app by default when z-index values are equal.
The container must exist when createPortal runs. If document.getElementById('portal-root') returns null, React throws "Target container is not a DOM element." Looking it up during render works in a client-only app, because the HTML is already loaded. It fails during server rendering, which is covered in a later chapter.
Option 3: create the container yourself
When a component should not depend on markup in index.html, create the node inside an effect and remove it afterward.
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
function OwnedPortal({ children }) {
const [container, setContainer] = useState(null);
useEffect(() => {
const node = document.createElement('div');
document.body.appendChild(node);
setContainer(node);
return () => {
document.body.removeChild(node);
};
}, []);
return container ? createPortal(children, container) : null;
}The first render returns null. The effect then creates andsetContainer triggers a second render that creates the portal. The cleanup function removes the node when the component unmounts, so you do not leave empty div` elements behind.
Creating the node during render is a mistake. Render can run more than once, and React may discard a render without ever committing it. Each run would leak a detached or attached node. Keep side effects in useEffect.
Letting the caller choose
A reusable component can accept the container as a prop and fall back to a default:
import { createPortal } from 'react-dom';
function Overlay({ children, container }) {
const target = container ?? document.body;
return createPortal(children, target);
}This is useful when an overlay must stay inside a specific region, such as a fullscreen element. Content outside an element in fullscreen mode is not displayed, so a toast portaled to body would be invisible.
Multiple portals in one container
Several portals can share one container. React appends each portal's output as children of that node, in the order the portals mount. Later portals paint above earlier ones when stacking values are equal. If order matters, such as a confirmation dialog opened from inside another modal, mount the confirmation after the first. Don't rely on z-index alone.
Deciding
- Start with
document.bodyfor one simple overlay. - Move to a
#portal-rootwhen you have several overlays or need to style them as a group. - Create the node in an effect when the component must be self-contained.
- Accept a
containerprop when callers need control, such as fullscreen regions.
Exercise
Why should you create a portal container with document.createElement inside useEffect rather than during render, and what must the effect's cleanup do?
Show answer
Render can run multiple times and may be discarded, so creating DOM nodes there leaks nodes and is a side effect. The effect runs only after commit. Its cleanup must remove the node from the document so unmounting leaves no stray elements.
Exercise
A component calls createPortal(children, document.getElementById('portal-root')) and React reports "Target container is not a DOM element." Name two likely causes.
Show answer
The #portal-root element is missing from the HTML, or the lookup ran before the element existed, for example during server rendering. Fixes: add the element to the HTML, or look it up inside an effect.