React Error: Target Container is not a DOM Element
Also make sure id set in index.html is same as the one you referring to in index.js
index.html:
<body>
<div id="root"></div>
<script src="/bundle.js"></script>
</body>
index.js:
ReactDOM.render(<App/>,document.getElementById('root'));
I figured it out!
After reading this blog post I realized that the placement of this line:
<script src="{% static "build/react.js" %}"></script>
was wrong. That line needs to be the last line in the <body>
section, right before the </body>
tag. Moving the line down solves the problem.
My explanation for this is that react was looking for the id in between the <head>
tags, instead of in the <body>
tags. Because of this it couldn't find the content
id, and thus it wasn't a real DOM element.
Just to give an alternative solution, because it isn't mentioned.
It's perfectly fine to use the HTML attribute defer
here. So when loading the DOM, a regular <script>
will load when the DOM hits the script. But if we use defer
, then the DOM and the script will load in parallel. The cool thing is the script gets evaluated in the end - when the DOM has loaded (source).
<script src="{% static "build/react.js" %}" defer></script>
webpack solution
If you got this error while working in React with webpack and HMR.
You need to create template index.html
and save it in src
folder:
<html>
<body>
<div id="root"></div>
</body>
</html>
Now when we have template with id="root"
we need to tell webpack to generate index.html which will mirror our index.html
file.
To do that:
plugins: [
new HtmlWebpackPlugin({
title: "Application name",
template: './src/index.html'
})
],
template
property will tell webpack how to build index.html
file.