Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ForEach inside of a map Javascript React not showing up

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 5×5

      {
        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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When I remove the forEach, the S component does show up.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading