简体   繁体   中英

Webpack, React & Babel, not rendering DOM

I finally after hours made my Webpack , React & Babel build setup, but when I try to just run a simple render Hello World it doesn't output anything in the DOM.

Here is my code.

 var React = require('react'); var ReactDOM = require('react-dom'); ReactDOM.render( <h1>Hello, world!</h1>, document.getElementById('content') ); 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <script src="bundle.js"></script> </head> <body> <div id="content"></div> </body> </html> 

And when I watch my bundle.js I can see it imports all the React & ReactDOM I need to run the render.

The test I'm running is from: https://facebook.github.io/react/docs/getting-started.html .

Getting this console error: Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.

Your bundle.js file is being loaded before the DOM has had time to load. This means that it won't be able to find your <div id="content"> when you have asked for it.

Try putting the script loader before the end of the body.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
</head>
<body>
    <div id="content"></div>
    <script src="bundle.js"></script>
</body>
</html>

When browsers find a <script> tag, they pause execution while they download the file. This means that your DOM has only partially rendered when your bundle.js script begins executing. So you would have essentially been passing undefined to the ReactDOM.render method.

If you have not had this issue in the past, perhaps you have been using the jQuery.ready event handler, which waits for the DOM to be loaded before executing.

bundle.js is executed when the content element isn't yet parsed an created. Just move your script element to the of the markup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM