Anyone know why this isn't generating any components?
sArray is a 2d array with a structure like a box [[1,2],[4,4]], but it's 5x5
{
sArray.map( (array) => {
console.log('inthemap');
array.forEach(element => {
console.log('intheEach');
return (
<div>
<S ticketValue={element}> </S>
</div>
)
});
})
}
When I run the page the Console logs the InTheMap and then the InTheEach 5 times, and it does this 5 times. Meaning I'm making 25 S components, but they do not show up.
When I remove the forEach, the S component does show up.
CodePudding user response:
There are two issues I see above:
- You are missing a
return
statement for the inner loop - You should be using
map
instead offorEach
since you are returning
{
sArray.map((array) => {
// you forget to return this
return array.map(element => {
return (
<div>
<S ticketValue={element}> </S>
</div>
)
})
})
}
Also quick note that this has a runtime complexity of O(n^2) which may be ok for smaller arrays, but will slow performance exponentially as they grow in size.
You may want to move this from outside the render
method and compute with useMemo
to prevent unnecessary re-renders:
https://reactjs.org/docs/hooks-reference.html#usememo
// compute this value only once (or add dependencies for when it should update)
const myExpensiveRender = useMemo(() => {
return sArray.map((array) => {
return array.map(element => {
return (
<div>
<S ticketValue={element}> </S>
</div>
)
}
},[])
return (
<>
{myExpensiveRender}
</>
)