HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
targetinvariantdom_registercomponentnotcontainerviolationelement

Problem

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

React.renderComponent(, document.body);


HTML:


  


What does this mean?

Solution

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:


  
  


and in the bundle.js, call:

React.render(, 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(, document.getElementById('root'));

Code Snippets

<html>
<head>
</head>
<body>
  <div id="root"></div>
  <script src="/bundle.js"></script>
</body>
</html>
React.render(<App />, document.getElementById('root'));
import ReactDOM from 'react-dom';

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

Context

Stack Overflow Q#26566317, score: 638

Revisions (0)

No revisions yet.