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

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?

This question is related to javascript dom reactjs

The answer is


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>

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'));
})

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! :-)


/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


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.


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.


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.


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:

<script>
  document.addEventListener("DOMContentLoaded", function(event) {
    console.log("DOM fully loaded and parsed");
  });
</script>

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

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

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


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

_x000D_
_x000D_
mport React from 'react';_x000D_
import ReactDOM from 'react-dom';_x000D_
import './index.css';_x000D_
_x000D_
var destination = document.querySelector('#container');_x000D_
_x000D_
   ReactDOM.render(_x000D_
<div>_x000D_
<p> hello world</p>_x000D_
</div>, destination_x000D_
_x000D_
_x000D_
 ); 
_x000D_
body{_x000D_
_x000D_
    text-align: center;_x000D_
    background-color: aqua;_x000D_
  padding: 50px;_x000D_
  border-color: aqua;_x000D_
  font-family: sans-serif;_x000D_
}_x000D_
#container{_x000D_
  display: flex;_x000D_
  justify-content: flex;_x000D_
_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
  <head>_x000D_
    <meta charset="utf-8" />_x000D_
   _x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1" />_x000D_
    <meta name="theme-color" content="#000000" />_x000D_
    <meta_x000D_
      name="description"_x000D_
      content="Web site created using create-react-app"_x000D_
    />   _x000D_
    <title> app  </title>_x000D_
  </head>_x000D_
  <body>_x000D_
 _x000D_
_x000D_
    <div id="container">_x000D_
      _x000D_
    </div>_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


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>

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)


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