#Create a star rating

14 messages · Page 1 of 1 (latest)

mint kiln
#

Hi guys,
This is for a React project, but it's more of a JS question I guess.
I have to create a star rating component.
I have a prop:value pair "rating": "5", (rating is out of 5), and access to 2 PNGs: a pink star and a grey star.
Must look like this

I'm quite puzzled by the approach to take, especially when it comes to the mixture of pink and grey stars for ratings < 5.

Any pointers please?
Cheers

mint kiln
#

Create a star rating

solar sapphire
#

You need to store the selected value in a state. Based on that value you can show X selected start and X unselected stars.

I did this in plain js, react + angular as well, fortunately it's not too hard to tackle you just need to think a little bit.

It depending on your approach, you can create different type of components and you can make it very flexible, numbers of starts, icon or image that should be shown, different event handles can be added etc...

mint kiln
#

Ok thanks @solar sapphire , I'll dig into states then

solar sapphire
trim dove
mint kiln
trim dove
mint kiln
#

It's pure display. Not interactive. But I have to display X number of stars according to the data

trim dove
# mint kiln It's pure display. Not interactive. But I have to display X number of stars acco...

Alright, so here's a structure on how I implemented in vanilla JS (the same way will work in React with some tweaks)


<div class="star-rating-container">
                <div class="star-rating-inner" style="">
                 </div>
             </div>
        
.star-rating-container{
   position: relative;
   
   word-break: pre;
   display: inline-block;
   
   color:#0003;
   margin-bottom: 0.75rem;
   overflow: hidden;
   margin-right: 0.25rem;
}
.star-rating-inner{
   word-break: pre;
   position: absolute;
   top: 0;
   left: 0;

   color: #2373A1;
   display: flex;
   overflow: hidden;
   
   
}

mint kiln
trim dove
mint kiln
#

I ended up going for something much simpler, using ternary operators ; no state needed

export default function StarRating(props) {
    const ratingRange = [1, 2, 3, 4, 5]
    const stars = ratingRange.map((item, index) => {
      return props.rating >= item ? 
        <img key={index} src={pinkVector} className="star" alt="icône étoile pour note du logement"/> : 
        <img key={index} src={greyVector} className="star" alt="icône étoile pour note du logement"/>
    })
    return (
      <div className="star-rating">
        {stars}
      </div>
    );
  };

Thanks for your help guys though. Shows me I have much to learn still!