. Advertisement .
..3..
. Advertisement .
..4..
Hi, It’s me again. I am having trouble with the “_registerComponent(…): Target container is not a DOM element” error. Please give me the best way to handle this error. This morning, after I was trying to run a program to create a trivial React example page, a message popped up on my screen saying something like this:
Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.
The following is the code that I used to create my program:
/** @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>
I’ve tried several approaches but am still unable to resolve this issue. Is there anyone who can help me?
Cause:
Keeping the
script
in thehead
and rendering onDOMContentLoaded
is a viable option. However, if you retain thescript
in thehead
in this case, thedocument
element will not be available when thescript
is launched. This is the reason why you’re getting the error: “_registerComponent(…): Target container is not a DOM element”.Solution:
First of all, your
script
should be placed at the bottom of thebody
, and the root component should be displayed to adiv
before it, as seen below:Then let’s order in the
bundle.js
as below:In this post, I’ll give you one more piece of advise. Unless you always render to a nested
div
instead of thebody
, the 3rd party code ( for example browser plugins, Google Font Loader,…) can alter the DOM node’sbody
when React does not anticipate it, resulting in strange issues that are difficult to track down and fix.I hope that my solutions will be useful for you to solve your “_registerComponent(…): Target container is not a DOM element” error.