[javascript] React Error: Target Container is not a DOM Element

I just got started using React so this is probably a very simple mistake, but here we go. My html code is very simple:

<!-- base.html -->
<html>
  <head>
    <title>Note Cards</title>
    <script src="http://fb.me/react-0.11.2.js"></script>
<!--     <script src="http://fb.me/JSXTransformer-0.11.2.js"></script> -->
    <script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
    {% load staticfiles %}
    <link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">
    <script src="{% static "build/react.js" %}"></script>
  </head>
  <body>
    <h1 id="content">Note Cards</h1>
    <div class="gotcha"></div>
  </body>
</html>

Note that I am using django's load static files here. My javascript is a bit more complex, so I won't post it all here unless someone requests it, but the line with the error is this:

React.renderComponent(
  CardBox({url: "/cards/?format=json", pollInterval: 2000}),
  document.getElementById("content")
);

After which I get the 'target container is not a DOM element error' yet it seems that document.getElementById("content") is almost certainly a DOM element.

I looked at this stackoverflow post, but it didn't seem to help in my situation.

Anyone have any idea why I'd be getting that error?

This question is related to javascript django dom reactjs

The answer is


I had encountered the same error with React version 16. This error comes when the Javascript that tries to render the React component is included before the static parent dom element in the html. Fix is same as the accepted answer, i.e. the JavaScript should get included only after the static parent dom element has been defined in the html.


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 got the same error i created the app with create-react-app but in /public/index.html also added matrialize script but there was to connection with "root" so i added

<div id="root"></div>

just before

<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/ materialize.min.js"></script>

And it worked for me .


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>

Also you can do something like that:

document.addEventListener("DOMContentLoaded", function(event) {
  React.renderComponent(
    CardBox({url: "/cards/?format=json", pollInterval: 2000}),
    document.getElementById("content")
  );
})

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.


For those that implemented react js in some part of the website and encounter this issue. Just add a condition to check if the element exist on that page before you render the react component.

<div id="element"></div>

...

const someElement = document.getElementById("element")
    
if(someElement) {
  ReactDOM.render(<Yourcomponent />, someElement)
}

Also, the best practice of moving your <script></script> to the bottom of the html file fixes this too.


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"></root>
    </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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to django

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip Pylint "unresolved import" error in Visual Studio Code Is it better to use path() or url() in urls.py for django 2.0? Unable to import path from django.urls Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' ImportError: Couldn't import Django Django - Reverse for '' not found. '' is not a valid view function or pattern name Class has no objects member Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries How to switch Python versions in Terminal?

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release