I am trying to print props of a react component but getting an error. Please help:
Snippet:
<!-- DOCTYPE HTML -->
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.min.js"></script>
<script src="http://fb. me/JSXTransformer-0.12.1.js"></script>
<!-- gap above is intended as else stackOverflow not allowing to post -->
</head>
<body>
<div id="div1"></div>
<script type="text/jsx">
//A component
var George = React.createClass({
render: function(){
return (
<div> Hello Dear!</div>
<div>{this.props.color}</div>
);
}
});
ReactDOM.render(<George color="blue"/>, document.getElementById('div1'));
</script>
</body>
</html>
I am expecting "Hello Dear!" and then next line "blue". But, I am getting this error instead.
Error:
As of React v16 React components can return an array. This was not possible prior to v16.
Doing this is simple:
return ([ // <-- note the array notation
<div key={0}> Hello Dear!</div>,
<div key={1}>{this.props.color}</div>
]);
Note that you need to declare a key for each element of the array. According to official sources, this might become unnecessary in future versions of React, but not as of right now. Also don't forget to separate each element in the array with ,
as you would normally with an array.
React Components can only return one expression, but you are trying to return two <div>
elements.
Don't forget that the render()
function is exactly that, a function. Functions always take in a number of parameters and always return exactly one value (unless void).
It's easy to forget, but you're writing JSX and not HTML. JSX is just a syntactic sugar for javascript. So one element would be translated as:
React.createElement('div', null, 'Hello Dear!');
This gives a React element, which you can return from your render()
function, but you cannot return two individually. Instead you wrap them in another element which have these div
s as children.
From the official docs:
Caveat:
Components must return a single root element. This is why we added a
<div>
to contain all the<Welcome />
elements.
Try wrapping these components in another component so that you only return one:
//A component
var George = React.createClass({
render: function(){
return (
<div>
<div> Hello Dear!</div>
<div>{this.props.color}</div>
</div>
);
}
});
ReactDOM.render(<George color="blue"/>, document.getElementById('div1'));
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