3

it can only return only one element tag in render.
In v16, we can render multiple elements by using an array.
so why cannot straightly write mutiple element tags in React?

render(){
  return(
    <div />
    <div />
  )
}

I mean that why cannot render multiple elements but not how to render mutiple elements.

Enivia
  • 192
  • 2
  • 11

3 Answers3

14

React implementation relies on constructing a tree like structure which it uses to for reconcilation. When you return multiple elements from React elements from the render method, the assumtion that the tree will have one root node for the Component will not longer hold, hence making it difficult to process reconcilation algorithm.

Thus react gives you a limitation to provide a root node. If you return an array of elements from v16 onwards, react will internally create a dummy node as the parent.

From version 16.2 onwards React provides a React.Fragment component, that provides a cleaner syntax to return multiple elements

render(){
  return(
    <React.Fragment>
       <div />
       <div />
    </React.Fragment>
  )
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • 1
    `the assumtion that the tree will have one root node for the Component will not longer hold, hence making it difficult to process reconcilation algorithm` --- How does React.Fragment solve this problem? – Aamir Khan May 27 '20 at 11:26
  • @AamirKhan React.Fragment gives you a dummy parent node to which multip;e elements can be treated as children – Shubham Khatri May 27 '20 at 11:30
  • 1
    Yes, but how does it work under the hood? Because the dummy parent doesn't show up in the DOM tree so I am confused as to how React gets around the original problem i.e. not having one root node. – Aamir Khan May 28 '20 at 08:05
4

React needs a parent element to render anything. You could put them in an array, or use a tool they gave for this exact purpose, the fragment component.

A fragment is just an empty node that won't show in the DOM allowing you to return multiple JSX components next to each other :

render(){
  return(
    <>
      <div />
      <div />
    </>
  )
}

If your linter is not a fan of this, you can use React.Fragment instead :

render(){
  return(
    <React.Fragment>
      <div />
      <div />
    </React.Fragment>
  )
}

The short answer to your question is... well this is just how React works and how their rendering engine is designed.

For now, multiple elements put together will not be interpreted as an array.

Treycos
  • 7,373
  • 3
  • 24
  • 47
-1

You can try

render(){
  return[
    <div> Div 1</div>,
    <div> Div 2</div>,
    <div> Div 3</div>,
    <div> Div 4</div>
  ]
}
Grigor Nazaryan
  • 567
  • 5
  • 18