react
dom_error
ai_generated
true
Error: Target container is not a DOM element. (createPortal)
ID: react/react-portal-target-missing
91%Fix Rate
93%Confidence
85Evidence
2022-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 18 | active | — | — | — |
Root Cause
ReactDOM.createPortal() called with a null or undefined DOM container. The target element does not exist in the DOM yet (timing issue) or the selector is wrong.
genericWorkarounds
-
95% success Add a dedicated portal root element in index.html and use getElementById
In index.html: <div id="portal-root"></div>. In component: createPortal(children, document.getElementById('portal-root'))Sources: https://react.dev/reference/react-dom/createPortal#rendering-a-modal-dialog-with-a-portal
-
89% success Use useEffect to create and append the portal container, with cleanup to remove it
const [container] = useState(() => document.createElement('div')); useEffect(() => { document.body.appendChild(container); return () => document.body.removeChild(container); }, [container]); return container ? createPortal(children, container) : null;
Dead Ends
Common approaches that don't work:
-
Use document.body as the portal target
50% fail
Appending directly to document.body can conflict with third-party scripts, modal libraries, and CSS stacking contexts. May break SSR where document is not available.
-
Create the DOM element dynamically inside the component render
60% fail
Creating DOM elements during render is a side effect; the element may be created multiple times in StrictMode and is not cleaned up properly
Error Chain
Preceded by:
Frequently confused with: