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

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>
      )
    });

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

>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>
  )
});
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