Search code examples
javascriptstringloopsconcatenationcomponents

How to concatenate the rating-bar markup of a star-rating component via a for-loop?


I have a rating number for 3 different products, and I am trying to render a star svg based of their rating number.
For example product-A has rate 3, I want to render star img, 3 times.
The maximum star they can have is 5.

I wrote a code like this:

const ratingHandler = (productRate) => {
  for (let i = 0; i < productRate + 1; i++) {
    console.log(productRate);
    return `<img src="assets/star.svg" alt="rating-star" />`;
  }
};

Product rate shows the rating number correctly in my console.log, but the render in the loop doesn't render based of that number.


Solution

  • Your function ends as soon as it first hits the return. You need to build up the complete string before returning:

    const ratingHandler = (productRate) => {
      let stars = '';
      for (let i = 0; i < productRate + 1; i++) {
        stars += `<img src="assets/star.svg" alt="rating-star" />`;
      }
      return stars;
    };