Sub topic 4
Choosing a portal container
This chapter assumes you can write function components with useState and useEffect. It also assumes you know what createPortal(children, container) does and how document.body and CSS stacking work. Here you decide what the second argument should be, because that choice affects styling, testing, server rendering and cleanup.
What the container is
The container is the real DOM node that receives the portal's children. React appends the portal's output to it and manages only that output. Any other children of the container stay untouched. This has three consequences:
- Several portals can share one container. Their output is appended in mount order.
- The container does not have to be empty, so
document.bodyworks. - React never creates or removes the container. You are responsible for it existing when
createPortalruns, and for removing it if you created it.
If the container is null or undefined, React throws Target container is not a DOM element. Most container bugs come down to that error.
The main options
| Container | Where it comes from | Strengths | Weaknesses |
|---|---|---|---|
| `document.body` | Always exists in the browser | No setup. Escapes almost every clipping parent. | Shares space with scripts, extensions and other libraries. Hard to style or isolate as a group. |
| Dedicated root such as `#portal-root` | You add it to the HTML next to the app root | One predictable place for overlays. Easy to style, inspect and target in tests. | Must exist before React renders. Needs a fallback. |
| Container created by the component | `document.createElement` inside an effect | Self-contained. Each instance gets its own node. | More code. Needs cleanup. Renders nothing on the first pass. |
| Element inside your own UI | A ref to a layout element | The content appears in a specific slot, such as a header. | The target must be mounted first. It can be clipped again by its own ancestors. |
Option 1: document.body
The modal in the previous chapter used document.body. It is the right default for small apps, demos and one-off overlays:
import { createPortal } from 'react-dom';
function Overlay({ children }) {
return createPortal(<div className="overlay">{children}</div>, document.body);
}This works when the code only runs in the browser and after the document exists. It is also the simplest way to guarantee the portal sits outside every wrapper your app renders.
The drawbacks show up in larger pages. Browser extensions, analytics snippets and other libraries also append to body. Your overlay then sits among nodes you do not control. CSS such as body > *:not(#root) { display: none } in a print stylesheet, or a global reset applied to body > div, will hit your portal content.
Option 2: a dedicated portal root
Most production apps add a second mount point next to the app root:
<body>
<div id="root"></div>
<div id="portal-root"></div>
</body>Now every overlay goes to one known place. You can give that node its own styles, an aria-live policy, or isolation: isolate. In the browser's inspector you can see all open overlays in one spot, and in tests you can assert on that one node.
A small wrapper keeps the lookup in one place:
import { createPortal } from 'react-dom';
function Portal({ children, containerId = 'portal-root' }) {
const container = document.getElementById(containerId) ?? document.body;
return createPortal(children, container);
}The ?? document.body fallback prevents the Target container is not a DOM element error when someone forgets the HTML element, for example in a test harness or a Storybook page. Decide on purpose whether you want that silent fallback. In a large codebase you might prefer a loud failure so that a missing #portal-root is caught early:
import { createPortal } from 'react-dom';
function StrictPortal({ children, containerId = 'portal-root' }) {
const container = document.getElementById(containerId);
if (!container) {
throw new Error(`Portal container #${containerId} was not found`);
}
return createPortal(children, container);
}Both versions read the DOM during render. That is fine in a client-only app whose HTML already contains the element before React starts. It breaks when the component renders on a server, because there is no document. The server rendering chapter covers that. The effect-based version in the next section is the usual remedy.
Option 3: creating the container yourself
Sometimes you cannot rely on markup. Examples are a component library that must work in any host app, or a widget that needs a private node per instance. In that case, create the element in an effect and remove it on cleanup:
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
function OwnedPortal({ children, className }) {
const [container, setContainer] = useState(null);
useEffect(() => {
const element = document.createElement('div');
if (className) element.className = className;
document.body.appendChild(element);
setContainer(element);
return () => {
document.body.removeChild(element);
};
}, [className]);
return container ? createPortal(children, container) : null;
}Points to notice:
- The component renders
nullon its first pass. The portal appears only after the effect runs andsetContainertriggers a second render. Children therefore mount one render later than you might expect. Code in a child that needs the portal DOM immediately, such as focusing an input, must run in the child's own effect. A parent's render or layout code cannot count on it. - The cleanup removes the element. Without it, every mount leaks an empty
divintobody. - React Strict Mode in development runs the effect, cleans up, and runs it again. The code above survives this because each run creates its own element and removes that same element.
- Because the state is
nullbefore the effect, the component is also safe during server rendering and hydration. It returnsnullon both sides, so the markup matches.
If you remove the container yourself, make sure React has already unmounted the portal's children. In the code above, the cleanup runs when the component unmounts, and React unmounts the portal content in the same commit. Removing a container that still holds mounted React content is the cause of errors such as Failed to execute 'removeChild' on 'Node'.
Option 4: a container inside your own UI
A portal does not have to go to body. You can target a node that another component renders, for example a toolbar slot that pages fill with their own buttons. The target is created by React, so you cannot read it with getElementById during the first render. Capture it with a callback ref stored in state:
import { useState } from 'react';
import { createPortal } from 'react-dom';
function Page({ slot }) {
return (
<main>
<p>Page content</p>
{slot ? createPortal(<button>Save</button>, slot) : null}
</main>
);
}
export default function Layout() {
const [slot, setSlot] = useState(null);
return (
<>
<header ref={setSlot} />
<Page slot={slot} />
</>
);
}Passing setSlot as the ref makes React call it with the DOM node after mount. The state change re-renders Layout, and Page then receives a real element. Use state here, not useRef. A ref change does not cause a re-render, so the portal would never appear.
This option keeps the content in a specific spot, but it does not escape clipping. If the header has overflow: hidden, a dropdown portaled into it is clipped like any other child. Use this option for placement, not for escaping overflow.
Styling and inheritance
A portal moves content in the DOM, so CSS follows the DOM position, not the React position. Two things catch people:
- Inherited properties such as
font-family,colorand CSS custom properties come from the container's ancestors. If your theme sets--accenton a wrapperdivinside#root, portal content under#portal-rootwill not see it. - Selectors that depend on ancestry, such as
.app .modal, stop matching.
There are three common fixes. Set theme variables on :root or body rather than on an inner wrapper. Copy the theme class onto the portal container. Or pass the theme through React context and apply the class inside the portal content. The context approach works because context follows the React tree, which the later chapter on context covers.
Stacking behaves differently from what you might expect. A portal escapes the stacking context of its React parent, but the container has its own position among its siblings. If #portal-root comes after #root in the DOM and neither creates a stacking context, positioned portal content with the same z-index paints above the app. Giving the app root isolation: isolate keeps its internal z-index values from competing with the overlays.
#root {
isolation: isolate;
}
#portal-root {
position: relative;
z-index: 1000;
}Several portals, one container
Opening a modal from inside another modal produces two portals in the same container. Each portal's children are appended when the portal mounts, so the later one is later in the DOM. For equal z-index values, it paints on top. That is usually what you want for a stack of dialogs. You should still not rely on mount order for anything beyond simple nesting. If a lower dialog re-renders, React updates it in place and does not move it, so order stays stable. If it unmounts and mounts again, it goes to the end of the container and can cover a dialog that was opened after it.
createPortal accepts an optional third argument, key. You rarely need it. It helps only when you return several portals as siblings from one component and React needs a stable identity for each.
Pitfalls specific to containers
- Reading the container too early.
document.getElementById('portal-root')returnsnullif the script runs before the element exists. Place the element in the HTML shell, or create it in an effect. - Changing the container between renders. If the
containerargument changes, React unmounts the portal content from the old node and mounts it into the new one. State inside the content is lost. Keep the container stable for the life of the component. - Forgetting cleanup. Every
createElementplusappendChildneeds a matchingremoveChild. - Sharing a container that something else clears. If other code sets
container.innerHTML = '', React's nodes disappear, and later updates throw. Treat the container as owned by React once a portal targets it. - Using a node in another document. Portals can target an iframe's
body, but thendocumentin your handlers refers to the parent page. Usecontainer.ownerDocumentwhen you add listeners.
Exercise
A component renders createPortal(<Tooltip />, document.getElementById('portal-root')). In production it works. In a unit test using the Testing Library render helper, it throws "Target container is not a DOM element." Why does this happen, and give two ways to fix it.
Show answer
The test document has no element with id portal-root, because the HTML shell that contains it is not part of the test render. getElementById returns null, so createPortal gets an invalid container. Fix one: create the element in the test setup (for example, append a div with id="portal-root" to document.body in a beforeEach, and remove it afterwards). Fix two: change the component to fall back to document.body when the lookup returns null, or to create its own container in an effect and render null until it exists.