react dom_error ai_generated true

Error: Target container is not a DOM element. (createPortal)

ID: react/react-portal-target-missing

Also available as: JSON · Markdown
91%Fix Rate
93%Confidence
85Evidence
2022-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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.

generic

Workarounds

  1. 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

  2. 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;

    Sources: https://react.dev/reference/react-dom/createPortal

Dead Ends

Common approaches that don't work:

  1. 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.

  2. 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

Leads to:
Preceded by:
Frequently confused with: