react
runtime_error
ai_generated
true
Error: Target container is not a DOM element. When using createPortal, the second argument must be a valid DOM node.
ID: react/portal-target-not-dom-element
88%Fix Rate
86%Confidence
1Evidence
2023-08-12First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| React 16.0.0 | active | — | — | — |
| React 17.0.2 | active | — | — | — |
| React 18.2.0 | active | — | — | — |
Root Cause
The second argument passed to ReactDOM.createPortal is not a valid DOM element (e.g., null, undefined, or a string selector), often because the target element hasn't been rendered yet or the selector is incorrect.
generic中文
传递给ReactDOM.createPortal的第二个参数不是有效的DOM元素(例如null、undefined或字符串选择器),通常是因为目标元素尚未渲染或选择器不正确。
Official Documentation
https://react.dev/reference/react-dom/createPortalWorkarounds
-
88% success Ensure the target DOM element exists before calling createPortal by using a ref or checking if the element is available in useEffect.
Ensure the target DOM element exists before calling createPortal by using a ref or checking if the element is available in useEffect.
-
95% success Define the target element in the HTML file (e.g., index.html) and ensure it's present before the React app mounts.
Define the target element in the HTML file (e.g., index.html) and ensure it's present before the React app mounts.
中文步骤
Ensure the target DOM element exists before calling createPortal by using a ref or checking if the element is available in useEffect.
Define the target element in the HTML file (e.g., index.html) and ensure it's present before the React app mounts.
Dead Ends
Common approaches that don't work:
-
Using document.querySelector('#root') without checking if the element exists
70% fail
If the DOM element is not yet mounted (e.g., in a component that renders before the target), querySelector returns null.
-
Passing a string like '#modal-root' directly to createPortal
90% fail
createPortal expects a DOM element, not a CSS selector string. It will throw an error because a string is not a node.
-
Using document.getElementById inside a component that runs before the target is rendered
60% fail
If the target div is defined in the same component's JSX, it may not exist in the DOM when the portal is created, leading to null.