In this tutorial, we'll build a reusable Star Rating component using React. This component will support both interactive and read-only modes, custom colors, and hover effects.
This is the kind of component that you often see in e-commerce sites or review apps.
Interactive Preview
Key features and requirements
-
Interactivity: The component switches between interactive and read-only modes based on the
readOnly
prop. -
Hover Effects: In interactive mode, hovering over stars shows a preview of the rating.
-
Customization: Supports custom colors, sizes, and number of stars.
-
Performance: Uses
React.memo
anduseMemo
to optimize rendering performance. -
Accessibility: Includes proper cursor styles and visual feedback for interactive elements.
Step 1: Setting Up the Component Interface
First, let's define the props interface for our component. This will help us understand what customization options our component will support.
Step 2: Creating the Star Icon Component
Let's create a memoized Star icon component that will be reused for each star in the rating. This helps with performance optimization.
Step 3: Setting Up the Main Component State
Now, let's set up the main component with its state and default props:
I have added some defaults, but you can of course change them to your liking.
Step 4: Implementing Interactive Handlers
Let's add the handlers for click and hover interactions. These will be needed to create a nice hover effect, in a way creating a sort of rating "preview", before the new rating is clicked.
Since we just want to preview a rating on hover, when the mouse leaves the component we want to display the original rating. Thus we implement a handleMouseLeave
handler to reset the hoverRating
to null
.
The handlers must also check for the readOnly
condition to avoid updating the rating when not needed.
Step 5: Star Styling Logic
Add the logic to determine each star's appearance:
We assign a const ratingToUse
and then we use such a variable to determine which color / fill a "star" should have.
Step 6: Generating the Stars
Then, all we need to do is display the star icons as a dynamic array whose length is determined by the maxStars
prop.
So we create the array of star components using the styling and interaction handlers:
Step 7: Final Component Assembly
Finally, let's put it all together in the return statement:
Usage Example
Full Source Code + Examples
Here you can get the full source code with examples!