Reputation: 1180
So, I have some working code, but I just feel like there is a solution where I can use just one .map() and I'm not seeing it.
The components are not siblings (they don't share the same parent component), so to solve this I just did .map() twice over the same array of objects, but I feel like that is a waste of resources and that there must be a better solution for this kind of situation.
Here's the code
<div className="pricepoints-form">
<Tabs className="tabs">
<TabList>
{
this.state.pricepointsData.map(pricepoint => (
<Tab className="tab">{pricepoint.name}</Tab>
))
}
</TabList>
{
this.state.pricepointsData.map(pricepoint => (
<TabPanel>
<Pricepoint
pricepoint={pricepoint}
displayLast4={this.state.displayLast4}
/>
</TabPanel>
))
}
</Tabs>
</div>
Upvotes: 0
Views: 5580
Reputation: 179246
Can using
.map()
twice over the same array be avoided even though the components the map() renders are not siblings?
Technically, yes it's possible. But lets look at what you're really optimizing away here.
map
is essentially a for
loop that assigns values to a new array:
// example
function map(transform) {
const ret = []
for (let i = 0; i < this.length; i++) {
ret.push(transform(this[i], i, this))
}
return ret
}
what this means is you could replace the map function with your own function that runs a loop and creates two arrays:
function myMap(transform1, transform2) {
const r1 = []
const r2 = []
for (let i = 0; i < this.length; i++) {
r1.push(transform1(this[i], i, this))
r2.push(transform2(this[i], i, this))
}
return [r1, r2]
}
Using this new function would be awkward at best:
const [tabs, panels] = myMap.call(this.state.pricepointsData, pricepoint => (...), pricepoint => (...))
...
<TabList>
{ tabs }
</TabList>
{ panels }
...
So the real question should be: Is this abstraction worth it?
And to that I have a counter-question:
What's larger, 2x1 or 1x2?
You could use two loops that each do one thing (2 map
calls), or you could use a single loop that does two things (1 myMap
call).
Upvotes: 1