# Error: The portal container is not a valid DOM element. Make sure the container element exists before calling createPortal.

- **ID:** `react/portal-container-not-mounted`
- **Domain:** react
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 92%

## Root Cause

ReactDOM.createPortal is called with a container that is null or undefined, usually because the target DOM element hasn't been mounted yet (e.g., document.getElementById('portal-root') returns null).

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| React 16.0+ | active | — | — |
| React 17.x | active | — | — |
| React 18.x | active | — | — |

## Workarounds

1. **Ensure the container element exists in the HTML before the React app mounts. Example: <div id="portal-root"></div> in index.html, then use const portalRoot = document.getElementById('portal-root'); ReactDOM.createPortal(children, portalRoot);** (95% success)
   ```
   Ensure the container element exists in the HTML before the React app mounts. Example: <div id="portal-root"></div> in index.html, then use const portalRoot = document.getElementById('portal-root'); ReactDOM.createPortal(children, portalRoot);
   ```
2. **Use useEffect to create the portal after the component mounts: useEffect(() => { setContainer(document.getElementById('portal-root')); }, []); Then conditionally render the portal only when container is not null.** (90% success)
   ```
   Use useEffect to create the portal after the component mounts: useEffect(() => { setContainer(document.getElementById('portal-root')); }, []); Then conditionally render the portal only when container is not null.
   ```
3. **For dynamic containers, create the container element in useEffect and append it to document.body: useEffect(() => { const el = document.createElement('div'); document.body.appendChild(el); setContainer(el); return () => document.body.removeChild(el); }, []);** (88% success)
   ```
   For dynamic containers, create the container element in useEffect and append it to document.body: useEffect(() => { const el = document.createElement('div'); document.body.appendChild(el); setContainer(el); return () => document.body.removeChild(el); }, []);
   ```

## Dead Ends

- **** — Refs are null during initial render; the container must exist in the DOM before createPortal runs. (90% fail)
- **** — The element is not attached to the DOM, so it's not a valid container for a portal. (85% fail)
- **** — Timers are unreliable and may still run before the DOM is ready; also causes race conditions. (75% fail)
