ReactDOM.render (): Invalid component element. Instead of passing a component class, be sure to create it by passing it to React.createElement

this error appears when I test the start of a reaction

my folder structure is simple:

app folder index.html index.js home.js webpack.config.js dist folder bundle.js 

index.html look like this

 <!DOCTYPE html> <html> <head> <title>hello world app</title> <link rel="stylesheet" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src= "../dist/bundle.js"></script> </head> <body> <div id="app"></div> </body> </html> 

index.js is as follows:

 var React = require('react'); var ReactDOM = require('react-dom'); var Home = require('./Home'); ReactDOM.render( Home, document.getElementById('app')); 

and home.js:

 var React = require('react'); var Home = React.createClass({ render: function(){ return( <div> hello from home </div> ) } }); module.exports = Home; 

I start compiling the code through this webpack configuration:

 module.exports = { entry:[ "./app/index.js" ], output: { path: __dirname + '/dist', filename: "bundle.js" }, module: { loaders : [ {test: /\.js$/, exclude : /node_modules/, loader: "babel-loader", query: { presets: ['react'] } } ] } } 

After compilation, I run the index.html file. And the error ReactDOM.render () appeared: Invalid component element .... What did I do wrong?

+6
source share
2 answers

ReactDOM.render takes an instance of the React class as its first argument. You pass the class directly.

So instead

 ReactDOM.render(Home, document.getElementById('app')) 

Try as shown below.

 ReactDOM.render(React.createElement(Home), document.getElementById('app')); 

or jsx copy

 ReactDOM.render(<Home />, document.getElementById('app')); 

In addition, it would be nice to do the following:

 <script src= "../dist/bundle.js"></script> 

at the bottom of the page, not the <head> , so the script can find <div id="app"></div> .

+14
source

You should use a render function like

 ReactDOM.render(<Home />, document.getElementById('app')); 
+1
source

All Articles