ReactJS报错「Target container is not a DOM element」求助
Hey there! Let's walk through the most common reasons you're hitting this error and how to fix them—since you mentioned it aligns with that known React issue, let's start with the usual suspects:
1. Your JavaScript loads before the DOM container exists
This is the #1 cause of this error. If your index.js script runs before the browser renders the <div> you're targeting, document.getElementById() will return null, and React can't mount your app.
Fix:
Move your <script> tag to the end of the <body> in index.html, right after your target container. This ensures the browser renders the container first before executing your React code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>React App</title> </head> <body> <!-- Your target container --> <div id="root"></div> <!-- Load JS after the container --> <script src="index.js"></script> </body> </html>
If you need to keep the script in the <head>, add the defer attribute—it tells the browser to load the script but wait until the DOM is ready to run it:
<head> <script src="index.js" defer></script> </head>
2. Mismatched container ID
Double-check that the ID you use in index.js exactly matches the ID in your HTML. Typos, capitalization differences, or wrong names will make React unable to find the container.
Example of a mismatch:
- HTML:
<div id="app"></div> - JS:
ReactDOM.createRoot(document.getElementById('root'))→ This will fail!
Fix it by making the IDs identical—stick with root (React's default) or whatever name you choose, just be consistent.
3. The container element is removed dynamically
Less common, but if other scripts or logic remove the target <div> before React tries to mount, you'll get this error. Check if any other code is manipulating the DOM where your container lives.
Quick debug test:
Add a console.log in your index.js to verify the container exists:
const container = document.getElementById('root'); console.log('Target container:', container); // Should log the div element, not null
If it logs null, circle back to the first two fixes—your script is running too early or the ID is wrong.
内容的提问来源于stack exchange,提问作者lordlabakdas

