React throws the error, target container is not a dom element, when we include the build script before the root element. The solution is to always include the build scripts before body closing tag </body>
.
Suppose the html structure of index.html
is –
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<meta name="theme-color" content="#000000" />
<link rel="manifest" href="/manifest.json" />
<title>Error Template</title>
<link href="/static/css/2.10306419.chunk.css" rel="stylesheet" />
<link href="/static/css/main.1b589238.chunk.css" rel="stylesheet" />
<script src="/static/js/2.537e346a.chunk.js"></script>
<script src="/static/js/main.119c9f53.chunk.js"></script>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
This file will create target container is not a dom element error because our scripts are loaded before out root
element.
The correct way is –
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<meta name="theme-color" content="#000000" />
<link rel="manifest" href="/manifest.json" />
<title>Error Template</title>
<link href="/static/css/2.10306419.chunk.css" rel="stylesheet" />
<link href="/static/css/main.1b589238.chunk.css" rel="stylesheet" />
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="/static/js/2.537e346a.chunk.js"></script>
<script src="/static/js/main.119c9f53.chunk.js"></script>
</body>
</html>
Now you can use it in your App.js
or index.js
files –
ReactDOM.render(
<MyComponent />,
document.getElementById("root")
);
    Tweet this to help others
Comments