Home > OS >  ForEach inside of a map Javascript React not showing up
ForEach inside of a map Javascript React not showing up

Time:05-28

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:

  1. You are missing a return statement for the inner loop
  2. You should be using map instead of forEach 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}
  </>
)
  • Related