0

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?

2
  • You can get a good idea from - alligator.io/react/rendering-arrays-in-react Commented Aug 7, 2019 at 4:49
  • @RonitMukherjee the blog doesn't answer my question. No point in downvoting a question when it's not answered yet. Commented Aug 7, 2019 at 4:57

3 Answers 3

1
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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, you're right about what the map returns here. I made a mistake. However, my question boils down to whether an array of components as shown in your last code snippet is similar to having components listed without an array, like the second approach in my question
@aakashdp yes they will lead to the same output.
0

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.

1 Comment

But if you see the second approach, it doesn't have an array, just two components. I wanted to understand how is it working with an array. The second approach is more intuitive
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.