Home > Software design >  how to perform a for loop inside map
how to perform a for loop inside map

Time:10-22

I am looping over records and inside there I have a star rating. If the star rating is 4, then I need a for loop to output 4 span tags. In php I had a foreach loop and inside that a for loop, but I am trying to convert it to React now.

  <?php foreach ( $foo as $bar ): ?>
           <?php for ( $x = 1; $x <= $stars; $x   ): ?>
               <span>&#9733;</span>
           <?php endfor;?>
           <?php for ( $x = 1; $x <= 5 - $stars; $x   ): ?>
               <span >&#9733;</span>
           <?php endfor; ?>
  <?php endforeach; ?>

React:

    {reviews.map((r) => (
      <>
        <div className="stars">
          {for loop would go here
           <span>&#9733;</span>
          }
        </div>
      </>
    ))}

CodePudding user response:

Create an array full of dummy values and use map again:

    {reviews.map((r) => (
      <>
        <div className="stars">
          {Array(stars).fill().map(() => <span>&#9733;</span>)}
        </div>
      </>
    ))}
  • Related