Sept 10, 2022
How to create a star rating system with ReactJs
Create a new component as StarRatingSystem.
We are going to use emotionJs to style our component. And React-icons for star icon.
1. ImportsImport 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 starsWhen 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
And that's it we have successfully created a 5 star rating system.