Skip to content Skip to sidebar Skip to footer

Why Does Putting A Div Tag Allow This React Code To Compile?

I found a solution to an issue on my own, but I am confused why it worked and would like to learn more. I have the following code that has a run time error: class ExampleClass exte

Solution 1:

Thats because you are literaly returning a object

Consider this:

classExampleClassextendsReact.Component {
  render() {
    const foo = [1, 2, 3]

    const jsx = foo.map((num) =><spankey={num}>
        {num}
      </span>
    );

    return ({jsx})
  }
}

You are returning an object with only one key called jsx, with the value of the variable jsx declared just before.

Every JSX should return at it's outer most wrapper must be:

  1. A pair of tags:

const Component = () => { return ( <div> ...JSX </div> ) }

  1. A React.Fragment:

const Component = () => { return ( <> ...JSX </> ) }

  1. A component:

const Component = () => { return ( <ReturnedComponent /> ) }

Solution 2:

When returning anything in jsx, it can only return one element. When returning only {jsx}, you are returning multiple span elements, which is not allowed.

Post a Comment for "Why Does Putting A Div Tag Allow This React Code To Compile?"