JS create rating score from 2 loops/arrays

Viewed 37

I am trying to create a basic rating component that looks like this:

◼◼◼◻◻ (score: 3 out of 5)

I have the following code in JSX:

var score = 3; 
var range = 5;

{ [...Array(range)].map((e, i) => (
  <div className="rating-item" data-rating-count={ i + 1 }></div>
)) }

this returns the range but doesn't show the rating score:

◻ ◻ ◻ ◻ ◻ 

How can I combine the score and range values and add a class name active to the rating items?

I'm trying to get the following HTML:

<div class="rating-item active" data-rating-count="1"></div>
<div class="rating-item active" data-rating-count="2"></div>
<div class="rating-item active" data-rating-count="3"></div>
<div class="rating-item" data-rating-count="4"></div>
<div class="rating-item" data-rating-count="5"></div>

Which will output: ◼◼◼◻◻

1 Answers

I think You need to modify your code like this

var score = 3; 
var range = 5;

{ [...Array(range)].map((e, i) => (
  <div className={"rating-item " + (i < score ? "active": "")} data-rating-count={ i + 1 }></div>
)) }
Related