React入门报错:Target container is not a DOM element问题咨询
Hey there, let's figure out why you're hitting this error and get your React app up and running smoothly.
1. Fix the ReactDOM.render Syntax
First, there's a small but critical syntax mistake in your index.js file. The way you're calling ReactDOM.render is passing a single comma-separated expression instead of the two required arguments (your component and the target DOM container).
Here's your original line:
ReactDOM.render((<App/> , document.getElementById('root')));
The parentheses around both values turn them into a comma expression, which returns the last value (the DOM element) as the only argument to render. That's not what we want. Correct it to pass the component first, then the container as separate arguments:
ReactDOM.render(<App/>, document.getElementById('root'));
2. Make Sure the #root Container Exists
React needs a DOM element to mount your app into. Double-check your public/index.html file has a <div> with the ID root:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>My React App</title> </head> <body> <!-- This is where React will render your App component --> <div id="root"></div> </body> </html>
If this element is missing, document.getElementById('root') will return null, which triggers the "Target container is not a DOM element" error.
3. Ensure Your Script Runs After the DOM is Ready
If your index.js script loads before the browser has parsed the #root element, it'll try to render to a non-existent container. To fix this:
- Move your script tag to the end of the
<body>section (right before</body>), so it runs after all DOM elements are loaded - Or add the
deferattribute to the script tag in the<head>to delay execution until the DOM is ready:<script src="/src/index.js" defer></script>
Test the Corrected Code
After these fixes, your index.js should look like this:
import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App'; // Debug check: This should log the <div id="root"> element, not null const rootElement = document.getElementById("root"); console.log(rootElement); ReactDOM.render(<App/>, rootElement);
Now fire up your app, and you should see "Hi There!" displayed without any errors.
内容的提问来源于stack exchange,提问作者Curious-programmer

