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?
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>
.
You have to use render function like
ReactDOM.render(<Home />, document.getElementById('app'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With