So, I am starting to learn React and I encountered this code and I am really confused.
The following code gives Error:
function getNum() {
return Math.floor(Math.random() * 10 + 1);
}
class Number extends React.Component {
render() {
const num = getNum();
let msg;
if (num % 2 == 0) {
msg = (
<div>
<h2>Even Number</h2>
<p>The number is: {num}</p>
</div>
);
} else {
msg = (
<div>
<h2>Odd Number</h2>
<p>The number is: {num}</p>
</div>
);
}
// THIS IS WHAT CAUSES ERROR
return {msg};
}
}
ReactDOM.render(<Number />, document.getElementById("root"));
But if I wrap the return inside a div like this <div>{msg}</div> the error goes away. I'm confused why is it so? Because the msg variable has a single parent so the return would also have a single parent, so why do I need that extra div container?