anon
anon

Reputation:

Why do I need an extra wrapper while returning in React?

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?

Upvotes: 2

Views: 38

Answers (1)

Danny Buonocore
Danny Buonocore

Reputation: 3777

By writing like this it's being interpreted as an object with a single key called msg. Without wrapping in JSX tags you can just write:

return msg;

The brackets should be used within JSX tags when you need to run a block of javascript or reference a variable.

Upvotes: 2

Related Questions