Share:

R

Rupali Yadav

Sept 10, 2022

How to create a star rating system with ReactJs

#javaScript

#reactjs

#customhook

#starratingsystem

#rating

#webexpe

#webexpe.com

#rupali yadav

#rupali

Star Rating Component in ReactJs | 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.

LOADING!


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

LOADING!


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.

LOADING!



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.

LOADING!


4. Display the rating

star-rating-system in react | rupali yadav
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 me on twitter, github and linkedIn for more such articles and other updates.
If you have any queries please write them below.

More from Author

What is hoisting in Javascript
What is hoisting in Javascript
Difference between pass by value and pass by reference in javascript
Difference between pass by value and pass by reference in javascript
How to use ref to style in react
How to use ref to style in react

Share:

Copyright © 2022 Web Expe

Privacy PolicyTerms and Conditions