Invariant Violation: _registerComponent(...): Target container is not a DOM element

JavascriptDomReactjs

Javascript Problem Overview


I get this error after a making trivial React example page:

>Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.

Here's my code:

/** @jsx React.DOM */
'use strict';

var React = require('react');

var App = React.createClass({
  render() {
    return <h1>Yo</h1>;
  }
});

React.renderComponent(<App />, document.body);

HTML:

<html>
<head>
  <script src="/bundle.js"></script>
</head>
<body>
</body>
</html>

What does this mean?

Javascript Solutions


Solution 1 - Javascript

By the time script is executed, document element is not available yet, because script itself is in the head. While it's a valid solution to keep script in head and render on DOMContentLoaded event, it's even better to put your script at the very bottom of the body and render root component to a div before it like this:

<html>
<head>
</head>
<body>
  <div id="root"></div>
  <script src="/bundle.js"></script>
</body>
</html>

and in the bundle.js, call:

React.render(<App />, document.getElementById('root'));

You should always render to a nested div instead of body. Otherwise, all sorts of third-party code (Google Font Loader, browser plugins, whatever) can modify the body DOM node when React doesn't expect it, and cause weird errors that are very hard to trace and debug. Read more about this issue.

The nice thing about putting script at the bottom is that it won't block rendering until script load in case you add React server rendering to your project.


Update: (October 07, 2015 | v0.14)

> React.render is deprecated, use ReactDOM.render > instead.

Example:

import ReactDOM from 'react-dom';

ReactDOM.render(<App />, document.getElementById('root'));

Solution 2 - Javascript

/index.html
<!doctype html>
<html>
  <head>
    <title>My Application</title>
    <!-- load application bundle asynchronously -->
    <script async src="/app.js"></script>
    <style type="text/css">
      /* pre-rendered critical path CSS (see isomorphic-style-loader) */
    </style>
  </head>
  <body>
    <div id="app">
      <!-- pre-rendered markup of your JavaScript app (see isomorphic apps) -->
    </div>
  </body>
</html>
/app.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';

function run() {
  ReactDOM.render(<App />, document.getElementById('app'));
}

const loadedStates = ['complete', 'loaded', 'interactive'];

if (loadedStates.includes(document.readyState) && document.body) {
  run();
} else {
  window.addEventListener('DOMContentLoaded', run, false);
}

(IE9+)

Note: Having <script async src="..."></script> in the header ensures that the browser will start downloading JavaScript bundle before HTML content is loaded.

Source: React Starter Kit, isomorphic-style-loader

Solution 3 - Javascript

the ready function can be used like this:

$(document).ready(function () {
  React.render(<App />, document.body);
});

If you don't want to use jQuery, you can use the onload function:

<body onload="initReact()">...</body>

Solution 4 - Javascript

just a wild guess, how about adding to index.html the following:

type="javascript"

like this:

<script type="javascript" src="public/bundle.js"> </script>

For me it worked! :-)

Solution 5 - Javascript

I ran into the same error. It turned out to be caused by a simple typo after changing my code from:

document.getElementById('root')

to

document.querySelector('root')

Notice the missing '#' It should have been

document.querySelector('#root')

Just posting in case it helps anyone else solve this error.

Solution 6 - Javascript

Yes, basically what you done is right, except you forget that JavaScript is sync in many cases, so you running the code before your DOM gets loaded, there are few ways to solve this:

  1. Check to see if DOM fully loaded, then do whatever you want, you can listen to DOMContentLoaded for example:

  2. Very common way is adding the script tag to the bottom of your document (after body tag):

  3. Using window.onload, which gets fired when the entire page loaded(img, etc)

    window.addEventListener("load", function() { console.log("Everything is loaded"); });

  4. Using document.onload, which gets fired when the DOM is ready:

    document.addEventListener("load", function() { console.log("DOM is ready"); });

There are even more options to check if DOM is ready, but the short answer is DO NOT run any script before you make sure your DOM is ready in every cases...

JavaScript is working along with DOM elements and if they are not available, will return null, could break the whole application... so always make sure you are fully ready to run your JavaScript before you do...

Solution 7 - Javascript

If you use webpack for rendering your react and use HtmlWebpackPlugin in your react,this plugin builds its blank index.html by itself and injects js file in it,so it does not contain div element,as HtmlWebpackPlugin docs you can build your own index.html and give its address to this plugin, in my webpack.config.js

plugins: [            
    new HtmlWebpackPlugin({
        title: 'dev',
        template: 'dist/index.html'
    })
],

and this is my index.html file

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="shortcut icon" href="">
    <meta name="viewport" content="width=device-width">
    <title>Epos report</title>
</head>
<body>
   <div id="app"></div>
   <script src="./bundle.js"></script>
</body>
</html>

Solution 8 - Javascript

In my case this error was caused by hot reloading, while introducing new classes. In that stage of the project, use normal watchers to compile your code.

Solution 9 - Javascript

For those using ReactJS.Net and getting this error after a publish:

Check the properties of your .jsx files and make sure Build Action is set to Content. Those set to None will not be published. I came upon this solution from this SO answer.

Solution 10 - Javascript

I ran into similar/same error message. In my case, I did not have the target DOM node which is to render the ReactJS component defined. Ensure the HTML target node is well defined with appropriate "id" or "name", along with other HTML attributes (suitable for your design need)

Solution 11 - Javascript

When you got:

Error: Uncaught Error: Target container is not a DOM element.

You can use DOMContentLoaded event or move your <script ...></script> tag in the bottom of your body.

> 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.

document.addEventListener("DOMContentLoaded", function(event) {
  ReactDOM.render(<App />, document.getElementById('root'));
})

Solution 12 - Javascript

it's easy just make basic HTML CSS js and render the script from js

mport React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

var destination = document.querySelector('#container');

   ReactDOM.render(
<div>
<p> hello world</p>
</div>, destination


	); 

body{

    text-align: center;
    background-color: aqua;
  padding: 50px;
  border-color: aqua;
  font-family: sans-serif;
}
#container{
  display: flex;
  justify-content: flex;

}

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
   
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />   
    <title> app  </title>
  </head>
  <body>
 

    <div id="container">
      
    </div>

  </body>
</html>

Solution 13 - Javascript

In my case of using jQuery - for some reason the window.onload doesn't act the same as jQuery's onload

So this one worked for me:

<script>
    $(function () {          <= replacing window.onload = function() {
      // Begin Swagger UI call region
      const ui = SwaggerUIBundle({
        ...

      window.ui = ui;
    });
  </script>

Solution 14 - Javascript

In my case, everything in the html file was set correctly (i.e. script was at the bottom of the body tag). The problem was solved by moving the definition of a component to a separate file from where the component was rendered to the ReactDOM.

So originally I had

import React from 'react';
import ReactDOM from 'react-dom';

class Comp extends React.Component {
    // component definition
}

ReactDOM.render(
    <Comp />,
    document.getElementById('root')
);

Problem was solved after I moved the component definition to a separate file and imported

import React from 'react';
import ReactDOM from 'react-dom';

import Comp from './CompFile';

ReactDOM.render(
    <Comp />,
    document.getElementById('root')
);

Solution 15 - Javascript

For my case I did mistake something below in index.js and corrected.

Error:

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

Solution: document.getElementById("root")

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root") // declared 
);

Solution 16 - Javascript

With webpack. there is a choice to load the html file with the htmlPlugin instead of us needing to define it. When this is the case, Webpack is going to create an html file that has the script tag over above the root-div element. One quick fix would be to add a new div to the dom dynamically and then write your react dom to it. This can be done on your reactDom render function defined (usually) on the index.js file as below.

import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
import { BrowserRouter as Router } from "react-router-dom";
ReactDOM.render(
      <Router>
          <App />
      </Router>,
      document.body.appendChild(document.createElement("div"))
    );

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDan AbramovView Question on Stackoverflow
Solution 1 - JavascriptDan AbramovView Answer on Stackoverflow
Solution 2 - JavascriptKonstantin TarkusView Answer on Stackoverflow
Solution 3 - Javascriptnils petersohnView Answer on Stackoverflow
Solution 4 - JavascripttaquilesView Answer on Stackoverflow
Solution 5 - JavascriptmangakidView Answer on Stackoverflow
Solution 6 - JavascriptAlirezaView Answer on Stackoverflow
Solution 7 - Javascriptghazaleh javaheriView Answer on Stackoverflow
Solution 8 - JavascriptMicrosView Answer on Stackoverflow
Solution 9 - JavascriptJecomsView Answer on Stackoverflow
Solution 10 - Javascriptanie codeskolView Answer on Stackoverflow
Solution 11 - JavascriptSky VoyagerView Answer on Stackoverflow
Solution 12 - JavascriptOmar bakhshView Answer on Stackoverflow
Solution 13 - JavascriptRicky LeviView Answer on Stackoverflow
Solution 14 - JavascriptAyush WView Answer on Stackoverflow
Solution 15 - JavascriptKARTHIKEYAN.AView Answer on Stackoverflow
Solution 16 - JavascriptBarath DView Answer on Stackoverflow