Paul Bennett

Aspiring developer.Based in London, UK

I’m an aspiring developer currently wading my way through Python, JavaScript and it's frameworks especially Vue.js. I'm mostly doing front-end development, I’m a sucker for beautiful UI and utility-first CSS. Always learning and creating, recent and my pinned open-source projects are displayed here.

Making a star rating in React.js

June 30th, 2020 · 3 min read


When I was attempting to create a card, that allows for a star rating. It wasn't that easy for me...especially when watching a TailWind tutorial that was using Vue.js

I did in the end manage to create my own star rating component.

    [...Array(5)].map((star, i) => {
        const ratingValue = i + 1;
        return (
            <AiFillStar color={ratingValue > card.rating ? 'grey' : 'teal'} />

Using the above I was able to create these delightful looking cards.

react card components

Step 1.

First, we need to create an empty array of 5 items by adding the following: [...Array(5)] which will take (star, i) as it's arguments we will then map over it. Giving us 5 items these items will be the star icon <AiFillStar /> which we will return.

Step 2.

We then need to create an iterator so we can give our stars a value of 1 - 5. const ratingValue = i + 1; using 1 allows us to start our array at 1 instead of 0.

Step 3.

In our return statement, we have our icon which is imported from react-icons with a color prop. We need to conditionally check if our ratingValue is greater than our card.rating to be able to produce the number of coloured stars we need. We do this by using an inline if-else with an conditional operator condition ? true : false..

Here we are comparing if ratingValue is greater than card.rating if true then produce grey stars if false produce teal stars.

<AiFillStar color={ratingValue > card.rating ? 'grey' : 'teal'} />

If you're wondering where my card. is coming from the star rating sits in another map method which is how we're using card.rating in our conditional:

<div className='cardContainer'>
    { => (
        <div className='card'>
            <img src={card.imgUrl} />

Below is the data set I used to get the card rating from.

const cardData = [
        beds: 3,
        baths: 2,
        title: 'Modern apartment in city center',
        price: 390000,
        formattedPrice: '£3,900.00',
        reviewCount: 69,
        rating: 4,
        beds: 1,
        baths: 2,
        title: 'Desert get away in the sun',
        price: 230000,
        formattedPrice: '£2,300.00',
        reviewCount: 108,
        rating: 3,
        beds: 2,
        baths: 1,
        title: 'Coastal apartment with communal pool',
        price: 900,
        formattedPrice: '£900.00',
        reviewCount: 2567,
        rating: 5,

That is it really...I got stuck with this a couple of time but now it's all working I am happy with the results. These star ratings are always the perfect edition to a card or anything that requires a rating.