Sub topic 10
Portals and server rendering
This chapter assumes you know function components, useState and useEffect, and the difference between the React tree and the DOM tree. It covers why createPortal fails during server rendering and how to make portal components safe.
Why portals break on the server
createPortal(children, container) needs a real DOM node as its second argument. On the server there is no document, so there is nothing to pass. Code like this crashes during server rendering:
import { createPortal } from 'react-dom';
function BrokenPortal({ children }) {
// ReferenceError on the server: document is not defined
return createPortal(children, document.body);
}Even when a container is available, a second problem remains. Hydration is the step where React attaches to HTML that the server already produced. React expects the first client render to produce the same output as the server. If the client renders a portal on that first pass and the server did not, the two disagree.
The fix: wait until the client is ready
Effects run only in the browser, and only after the first render has been committed. You can use that to delay the portal. Look up the container inside an effect and store it in state. Until then, render nothing.
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
function ClientPortal({ children, containerId = 'portal-root' }) {
const [container, setContainer] = useState(null);
useEffect(() => {
setContainer(document.getElementById(containerId));
}, [containerId]);
return container ? createPortal(children, container) : null;
}The sequence is:
- The server renders
null, so the HTML contains nothing for this component. - The client hydrates and also renders
null. The output matches, so there is no mismatch warning. - The effect runs and sets
container. - React re-renders and creates the portal.
Where the container comes from
The container node must exist in the page HTML before the effect runs. A common approach is to add an empty element to your document template, next to your app root:
<body>
<div id="root"></div>
<div id="portal-root"></div>
</body>If the element is missing, getElementById returns null. The component above then keeps rendering null and the modal never appears, with no error. Check the container ID first when a portal stays invisible.
Trade-offs of this approach
- No portal content in the server HTML. Search engines and users with slow JavaScript do not see it. This is usually fine for modals, tooltips and popovers, which appear after a user action.
- One extra render. The portal content appears on the second render. For content shown only after a click, this is not noticeable.
- Content that must be visible at first paint. If a portal must appear immediately, consider placing that content in the normal tree and positioning it with CSS instead.
A modal that opens on a click avoids most of these concerns. The component that calls createPortal only mounts after the user acts, which is always after hydration. In that case a direct document.body call is safe, because it never runs on the server. The ClientPortal wrapper matters when a portal may render on the first pass, for example a modal that starts open.
Using the wrapper
Wrap portal content in ClientPortal, and the rest of your components stay unchanged:
function Toast({ message }) {
return (
<ClientPortal>
<div role="status" className="toast">
{message}
</div>
</ClientPortal>
);
}Events and context still flow through the React tree, so Toast can read context from its ancestors as usual once the portal appears.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `document is not defined` on the server | `createPortal` called with `document.body` during render | Look up the container in an effect |
| Hydration mismatch warning | Portal rendered on the first client pass | Render `null` until the effect has run |
| Portal never appears | Container ID missing from the HTML | Add the element to the template or check the ID |
| Portal appears, then disappears on navigation | Container is inside a part of the page that is replaced | Put the container outside the app root |
Exercise
A modal component calls createPortal(children, document.body) directly in its render function. It works when opened by a button click but throws document is not defined when a page loads with the modal open by default. Why does it differ, and how do you fix the second case?
Show answer
A modal opened by a click mounts only in the browser, after hydration, so document exists. A modal that starts open renders during server rendering, where document does not exist. Fix it by looking up the container in useEffect, storing it in state, and rendering null until it is set, as in ClientPortal. The server and the first client render then both produce null, so hydration matches.
Exercise
Your portal wrapper uses document.getElementById('portal-root') in an effect, but the modal never shows up and no error appears. What do you check first?
Show answer
Check that an element with the id portal-root exists in the page HTML. If it is missing, getElementById returns null, and the wrapper keeps rendering null without raising an error.