Enivia
Enivia

Reputation: 192

Why return multiple elements in React is not allowed?

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.

Upvotes: 3

Views: 6542

Answers (3)

Grigor Nazaryan
Grigor Nazaryan

Reputation: 577

You can try

render(){
  return[
    <div> Div 1</div>,
    <div> Div 2</div>,
    <div> Div 3</div>,
    <div> Div 4</div>
  ]
}

Upvotes: -1

Shubham Khatri
Shubham Khatri

Reputation: 281656

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>
  )
}

Upvotes: 16

Treycos
Treycos

Reputation: 7492

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.

Upvotes: 4

Related Questions