Sub topic 12
Pitfalls and best practices
This chapter assumes you have read the earlier chapters. You should know createPortal, the difference between the React tree and the DOM tree, and how events and context cross a portal. It collects the mistakes that show up most often in real projects and gives a checklist for avoiding them.
Pitfall 1: the container does not exist
createPortal throws if its second argument is not a DOM element. A typical cause is a lookup that runs before the element exists, or an id that is misspelled:
// Throws "Target container is not a DOM element" when the id is missing
createPortal(children, document.getElementById('portal-rot'));Two fixes work well:
- Put the container in
index.html(for example<div id="portal-root"></div>) next to your app root. - Use
document.bodywhen you do not need a dedicated node.
If the container may be absent, look it up in an effect and render null until you have it. The ClientPortal component from the server rendering chapter does this.
Pitfall 2: touching `document` during server rendering
document does not exist on the server. Code like createPortal(children, document.body) crashes there if it runs during render. Two safe patterns:
- Render the portal only after a user action, such as opening a modal. This never happens during server rendering or hydration.
- Resolve the container in
useEffect, so the first client render matches the server HTML.
Pitfall 3: leaking side effects
Portal components often attach things outside React's normal flow: a keydown listener on document, a scroll lock on body, or focus moved into the dialog. Each one needs cleanup. Another common bug is putting an unstable onClose in the effect dependencies. The effect then re-runs on every parent render, which re-locks scroll and steals focus again. Store the callback in a ref instead.
import { useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
function Modal({ onClose, children }) {
const dialogRef = useRef(null);
const onCloseRef = useRef(onClose);
useEffect(() => {
onCloseRef.current = onClose;
});
useEffect(() => {
const previouslyFocused = document.activeElement;
const previousOverflow = document.body.style.overflow;
document.body.style.overflow = 'hidden';
dialogRef.current.focus();
function handleKeyDown(event) {
if (event.key === 'Escape') onCloseRef.current();
}
document.addEventListener('keydown', handleKeyDown);
return () => {
document.removeEventListener('keydown', handleKeyDown);
document.body.style.overflow = previousOverflow;
if (previouslyFocused instanceof HTMLElement) previouslyFocused.focus();
};
}, []);
return createPortal(
<div className="backdrop" onClick={() => onCloseRef.current()}>
<div
ref={dialogRef}
className="dialog"
role="dialog"
aria-modal="true"
tabIndex={-1}
onClick={(e) => e.stopPropagation()}
>
{children}
</div>
</div>,
document.body
);
}The cleanup function restores everything the effect changed: the listener, the scroll lock, and the focus position. Render <Modal> conditionally ({open && <Modal ... />}) so that mounting and unmounting match opening and closing.
Pitfall 4: surprise event bubbling
React events bubble along the React tree, so a click inside a portal reaches onClick handlers on its React ancestors. A card with onClick={openDetails} that contains a modal will reopen itself whenever the modal is clicked. Either stop propagation at the portal boundary or move the portal out from under the clickable element.
Native listeners follow the DOM tree instead. A parent.addEventListener('click', ...) on a plain DOM node will not see clicks from portal content. Mixing the two models is a frequent source of "outside click" bugs. For outside-click detection, check event.target against a ref to the portal content, not against the parent element.
Pitfall 5: styles that no longer apply
Portal content sits under document.body, not under its React parent. CSS rules that depend on the DOM ancestor, such as .card .tooltip { ... }, stop matching. Inherited properties like font-family and color now come from body. Style portal content with its own classes, and set any inherited values explicitly.
Z-index also still matters. Portal nodes compete with other children of body. Pick a documented z-index scale, and expect later-mounted portals to appear above earlier ones when their z-index is equal.
Quick diagnosis
| Symptom | Likely cause | Fix |
|---|---|---|
| "Target container is not a DOM element" | Missing or misspelled container | Add the node to the HTML or use `document.body` |
| `document is not defined` on the server | Container read during render | Resolve it in an effect |
| Page cannot scroll after closing | Scroll lock never undone | Restore `overflow` in cleanup |
| Parent handler fires on modal click | Bubbling through the React tree | Stop propagation at the portal |
| Styles look wrong inside the portal | Ancestor-based CSS selectors | Use self-contained classes |
Best practices
- Keep one stable container, or use
document.body, instead of creating nodes on every render. - Clean up everything an effect starts.
- Render portals conditionally so they mount only when visible.
- Treat the React tree as the source of truth for events and context, and the DOM tree as the source of truth for CSS and native listeners.
- Test with
screenqueries, which searchdocument.bodyand so find portal content.
Exercise
A Card component has onClick={selectCard} and contains a <Modal> rendered with createPortal(..., document.body). Clicking inside the modal selects the card. Why does this happen, and what is one way to prevent it?
Show answer
React events bubble along the React tree, and the modal is still a child of Card there, so the click reaches selectCard. Prevent it by calling event.stopPropagation() in an onClick on the modal's outer element, or by rendering the modal outside Card in the component tree.