Rupali Yadav

Sept 10, 2022

How to create a star rating system with ReactJs






Star Rating Component in React js | Rupali Yadav
In this article we are going to create a 5 star rating system. So, let's dive in.

Create a new component as StarRatingSystem.
We are going to use emotionJs to style our component. And React-icons for star icon.

1. Imports

Import AiFillStar icon from react-icons, css from emotion and useState from react as shown below.


Create a component with name StarRating and declare a state as shown below.


2. Logic that we are going to use.

  • The selectedStar state is basically going to contain the index of the star out of the 5 stars that has been clicked by the user. Initially set to a empty String
  • In the jsx, we are going to check if the index of the individual star is less or equal to the selected star's index. If yes, we will change their color to yellow else it wilh have default grey color.

Create an array for 5 stars and loop as shown below to avoid redundant code for the 5 stars. As user is going to have a click action on the stars we are using buttons for the stars.
Once we are done writing the basic star rating structure let's add some basic styling for the stars as shown below.


3. Add Onclick on the stars

When the user clicks a star we will capture the star index and store it in selectedStar as shown below and compare the star index with the selected star's Depending upon above comparison we will send a boolean to the icon css method to display yellow or default grey color as shown in below code snippet.


4. Display the rating

Now that we have our rating system's logic ready, the only thing left is to display the final rating in a number format. For that add the below code that displays the rating out of 5.

And that's it we have successfully created a 5 star rating system.

Thanks for reading with us till here 🙂.
If this article helped you please follow us on github and twitter.
Also follow me on twitter. I post javascript concepts and utility code snippets.

Copyright © 2022 Web Expe

Privacy PolicyTerms and Conditions