Lazy Panda

Developer

Posts
57
Comments
48
Likes
76
Posts
57
Comments
48
Likes
76
sidebar

How to create a Rating component using React or NextJs

Mainly in an e-commerce application, we do have a review and ratings for all products. In this article, I will create a star rating component using react and convert 0 - 100% (percent) value into 1 to 5-star representation. This is what the following will look like. 

React star like rating component with percent value

 

Let's get started by creating an application using the create-react-app command like the below - 

npx create-react-app rating-app

 

Then create a ratings.js file along with the ratings.module.css file. Here, the idea is we are going to deal with two sets of star icons. One with filled with a golden color and another is filled with white color. Here is the two icon - 

 


Understanding the initializations, props, and callback - 

The Rating component has a few props for configuration for your needs - 

Rating.propTypes = {

ratingInPercent: number.isRequired,

iconSize: string,

showOutOf: bool.isRequired,

enableUserInteraction: bool.isRequired,

onClick: func

};

  • ratingInPercent: <Should be number and value from 0 to 100>
  • iconSize:<Should be string, can be 's', 'm' and 'l'>
  • showOutOf: <Boolean true/false, for handling out 5 or not>
  • enableUserInteraction: <Boolean true/false>
  • onClick: <if user interaction is enabled, then prompt user which star he/she has selected>

 

 


Demo time:

So, the custom rating component is ready to use, feel free to modify yourself based on your needs. And let me know about your requirement so I can add more features to it. Please share and add your comments below.

Happy Coding!

-LP