1

I just started learning web dev and I'm a little confused by this one thing in ReactJS. In my App component's render function, if I return JSX without an overarching div:

render() {
  return (
    <h1 style={headerStyle}>Todo List</h1>
    <Todo todos={this.state.todos}/>
  );
 }

I get an error:

./src/App.js
  Line 29:9:  Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?

  27 |      return (
  28 |         <h1 style={headerStyle}>Todo List</h1>
> 29 |         <Todo todos={this.state.todos}/>
     |         ^
  30 |      );
  31 |   }
  32 | }

but once I add a div:

render() {
     return (
        <div>
          <h1 style={headerStyle}>Todo List</h1>
          <Todo todos={this.state.todos}/>
        </div>
     );
  }
}

everything works fine.

Why is the div necessary? Or if its not actually necessary, what else could I be doing wrong?

Norbu Sonam
  • 97
  • 1
  • 7

5 Answers5

3

In react you must have a wrapper.

Either you can use html tag like- div or fragment

return (
        <div>
          <h1 style={headerStyle}>Todo List</h1>
          <Todo todos={this.state.todos}/>
        </div>
     );

or fragment if you don't want any additional html tag

return (
        <>
          <h1 style={headerStyle}>Todo List</h1>
          <Todo todos={this.state.todos}/>
        </>
     );

or

 return (
        <React.Fragment>
          <h1 style={headerStyle}>Todo List</h1>
          <Todo todos={this.state.todos}/>
        </React.Fragment>
     );

for reference https://reactjs.org/docs/fragments.html

akhtarvahid
  • 9,445
  • 2
  • 26
  • 29
2

Please use React Fragment to avoid additional element to render in the dom like div element.

class Columns extends React.Component { 
  render() { 
    return ( 
      <React.Fragment>  
        <h2>Hello</h2> 
        <p>How you doin'?</p> 
      </React.Fragment> 
    ); 
  } 
} 
1

A React element has to have a single root element. If you don’t want the div you can use a fragment:

<>
  <h1 style={headerStyle}>Todo List</h1>
  <Todo todos={this.state.todos}/>
</>

I’m not an expert on the internals of React, but my intuition is that the rendering requires a root node to get a handle on a list of children to iterate over. The tree has to have a root.

ray
  • 26,557
  • 5
  • 28
  • 27
1

You cannot have sibling html elements at root level. If you do not want the parent element, use array

render() {
  return ([
    <h1 style={headerStyle}>Todo List</h1>,
    <Todo todos={this.state.todos}/>,
  ]);
}

See - Reference

random
  • 7,756
  • 3
  • 19
  • 25
1

You can only return a single expression in JavaScript, so react needs you to return a single parent element. You should use fragments in this case if you don't need the parent div https://reactjs.org/docs/fragments.html