Home > Blockchain >  Should I Render react components as an array of components
Should I Render react components as an array of components

Time:07-18

I have a simple react component that directly renders several children:


return (
<header>
   <img src={logo}/>
   <h1>My Site</h1>
   <nav>...</nav>
</header>
);

Are there drawbacks/benefits of rendering this component as an array of components:


return (
<header>
   {[
     <img key="1" src={logo}/>,
     <h1  key="2">My Site</h1>,
     <nav key="3">...</nav>
   ]}
</header>
);

CodePudding user response:

I don't suggest using an array like that since it impacts readability negatively, and from what I know it does not have any benefits.

I only see this being used when someone is generating components programmatically, like when you're using Array.prototype.map() for example on an array of objects to create a new array of components with props populated from the array of objects.

CodePudding user response:

If you're thinking in terms of performance, there will probably be some slight drawbacks if you take into consideration the code used to generate the list of elements.

But I don't think that would be too much of a concern, what really bothers me, in this case, is the readability since you can write the same code without the brackets and curly braces to make that part a list of components, it's just harder to read and it could confuse someone else working in the same codebase.

As an alternative I can think of atm, you can extract that JSX into a component if you need to have it hidden from your render function.

CodePudding user response:

Why would you render as an array? I see no benefit. The drawback is that it's confusing to read, best to keep it as close to HTML syntax as possible until you need to introduce JS.

CodePudding user response:

You shouldn't use an array for this. if you can create smaller components for whatever inside it can be more beneficial for the redability

  • Related