ReactJs报错:Target container is not a DOM element 排查求助
Hey there! That error is super common when you're starting out with React—let's break down the most likely issues and how to fix them quickly:
1. Your React script is running before the DOM loads
React tries to mount your app into a DOM element that doesn't exist yet because your index.js is loading before the browser has parsed the container element.
Fixes:
- Move your script tag to the end of the
<body>in yourindex.htmlfile, right before the closing</body>tag. This way, the browser loads all DOM elements first before running your React code:<!-- public/index.html --> <body> <div id="root"></div> <!-- Script goes here --> <script src="../src/index.js"></script> </body> - If you need to keep the script in the
<head>, add thedeferattribute to it. This tells the browser to load the script after the DOM is ready:<head> <script src="../src/index.js" defer></script> </head>
2. You've got a typo in your container element's ID
Double-check that the ID you're targeting in index.js matches exactly what's in your index.html—IDs are case-sensitive!
For example, if your HTML has:
<div id="app-container"></div>
Your React code should use the same ID:
// src/index.js import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; // Correct ID here const root = ReactDOM.createRoot(document.getElementById('app-container')); root.render(<App />);
3. You forgot to add the container element entirely
Make sure your index.html actually has a div (or any DOM element) for React to mount into. This is the most common oversight for beginners!
Add this to your public/index.html inside the <body> tag:
<div id="root"></div>
Then ensure your index.js targets this exact ID.
If none of these fix it, pop open your browser's DevTools (F12) and run document.getElementById('your-target-id') in the console—if it returns null, that confirms the element isn't available when React tries to use it.
内容的提问来源于stack exchange,提问作者user3334226

