Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why return multiple elements in React is not allowed?

Tags:

reactjs

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.

like image 592
Enivia Avatar asked Dec 01 '25 05:12

Enivia


1 Answers

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>
  )
}
like image 143
Shubham Khatri Avatar answered Dec 08 '25 15:12

Shubham Khatri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!