Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

this error shows up when I test run react

my folder structure is simple like this:

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 like this:

var React = require('react');
var ReactDOM = require('react-dom');
var Home = require('./Home');

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

and home.js like this:

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

I run compile the code via this webpack config:

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 compiling, I run the file index.html. And the error ReactDOM.render(): Invalid component element... showed up. What I've done wrong?

like image 996
angry kiwi Avatar asked Mar 29 '16 07:03

angry kiwi


2 Answers

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

So instead of

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

Try like below.

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

or the JSX counterpart

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

Also, it would probably be a good idea to put like below.

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

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

like image 59
dannyjolie Avatar answered Sep 26 '22 14:09

dannyjolie


You have to use render function like

ReactDOM.render(<Home />, document.getElementById('app'));
like image 30
Dhaval Patel Avatar answered Sep 25 '22 14:09

Dhaval Patel