How to create dynamic star rating based on value in array object?

I am trying to create a for loop inside td but i am getting error.

The product object has a rating, and I need to create a number of star using fontawesome based on the rating in the object

  {
          productId: 2,
          productName: 'Garden Cart',
          productCode: 'gdn 0011',
          available: 'March 19, 2019',
          price: '19.95',
          rating: 4,
        },
    let product = this.state.products.map((x) => {
      return (
        <tr>
          <td></td>
          <td>{x.productName}</td>
          <td>{x.productCode}</td>
          <td>{x.available}</td>
          <td>{x.price}</td>
          <td>
            <i class="fas fa-star"></i> //I need to create 4 star based on the object
          </td>
        </tr>
      )
    });

>Solution :

You can use an empty array with N element and map over it:

{[...new Array(4)].map(() => <i class="fas fa-star"></i>)}

Your code should look like this:

let product = this.state.products.map((x) => {
  return (
    <tr>
      <td></td>
      <td>{x.productName}</td>
      <td>{x.productCode}</td>
      <td>{x.available}</td>
      <td>{x.price}</td>
      <td>
        {[...new Array(x.rating)].map(_ => <i className="fas fa-star"></i>)}
      </td>
    </tr>
  )
});

Leave a Reply