StarRating
A component for collecting rating feedback using stars
The StarRating
component can be used to let users to select a rating or to simply just show a star rating.
It supports hover effects, click selection, and both controlled and uncontrolled usage.
Usage
Uncontrolled Usage
javascript
1import StarRating from "@/components/atoms/StarRating"; 2 3<StarRating rating={5}/>
Controlled Usage
javascript
1import { useState } from "react";
2import StarRating from "@/components/atoms/StarRating";
3
4export default function FeedbackForm() {
5 const [rating, setRating] = useState(3);
6
7 return (
8 <div>
9 <h2>Please rate your experience:</h2>
10 <StarRating
11 totalStars={5}
12 rating={rating}
13 onRatingChange={setRating}
14 responsive
15 color="yellow"
16 />
17 </div>
18 );
19}
Props
Prop | Type | Default | Description |
---|---|---|---|
totalStars | number | 5 | The total number of stars to display. |
rating | number | undefined | The current rating if you want to control the component externally. If provided, the component becomes controlled. |
onRatingChange | (newRating: number) => void | undefined | Callback that fires when the user selects a new rating. Use this to control the rating from outside the component. |
responsive | boolean | false | Enables hover & click interactivity. If false, the stars will only reflect the static rating and will not respond to hover or click. |
color | string | "yellow" | The base color for filled stars (uses tailwind.config). |
initialRating | number | 0 | If the component is used in an uncontrolled fashion (no rating prop), this sets the initial rating. |
className | string | "" | Additional Tailwind classes for the container. |
...props | object | - | Any other valid <div> attributes (e.g. role , aria-* , etc.). |
StarRating
supports both controlled (via the rating
and onRatingChange
props) and uncontrolled usage (via the initialRating
prop).
Examples
Basic Uncontrolled StarRating
To use StarRating
in an uncontrolled fashion, simply provide the initialRating
prop and set responsive
to false
.
You can also tweak the totalStars
and color
props to customize the component.