aakashdp
aakashdp

Reputation: 143

How does render work with an array of components in React

Let's suppose we do the following in the React's render method

componentArr = [Component1, Component2]

<div>
    componentArr.map(Component => <Component />)
</div>

here, 'map' returns the following array, making the above code equivalent to

<div>
    [<Component1 />, <Component2 />]
</div>

which is different from

<div>
    <Component1 />
    <Component2 />
</div>

However, the first approach also works and has the same result as the second one. Why is that?

Upvotes: 0

Views: 55

Answers (3)

aakashdp
aakashdp

Reputation: 143

So, it looks like this was introduced in React v16.0 as per the official documentation https://reactjs.org/blog/2017/09/26/react-v16.0.html#new-render-return-types-fragments-and-strings

Upvotes: 0

Joseph D.
Joseph D.

Reputation: 12174

componentArr.map(component => <Component />)

here, 'map' returns the following array, making the above code equivalent to

<div>
    [<Component1 />, <Component2 />]
</div>

This statement is wrong.

It is equivalent to:

<div>
    {
      [Component1, Component2].map(
        component => {
          return component;
        }
      }
    }
</div>

So the return for map is (in between {}):

<div>
  {[
    <Component1 />,
    <Component2 />
  ]}
</div>

which React treats as a component tree for rendering in between braces {}. See Rendering list of multiple components.

Upvotes: 1

Dinesh Kumar
Dinesh Kumar

Reputation: 488

It works both the way either by using map or by passing an array directly because map in javaScript return you with an array. Let's take this simple example(Try it in console).

let arr = [1,2,3,4,5,6];
console.log(arr.map(e=>e+2));
OUTPUT:- [3, 4, 5, 6, 7, 8] 

Specific thing that came out of React 16, we want to look at is the ability to render multiple children using an array of components. This is a clear timesaver because it allows us to cram as many into a render instead of having to do it one-by-one.

Upvotes: 0

Related Questions