简体   繁体   中英

Should I Render react components as an array of components

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

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.

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM