UI Prototype · Star Rating
Rate your experience with a simple star rating.
"use client";
import { useState } from "react";
import "./StarRating.css";
type StarRatingProps = {
maxStars?: number;
initialRating?: number;
onChange?: (rating: number) => void;
};
function StarIcon({ filled }: { filled: boolean }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
className={`star-icon ${filled ? "star-icon-filled" : ""}`}
fill={filled ? "currentColor" : "none"}
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth="2"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"
/>
</svg>
);
}
export default function StarRating({
maxStars = 5,
initialRating = 0,
onChange,
}: StarRatingProps) {
const [rating, setRating] = useState(initialRating);
const [hoverRating, setHoverRating] = useState(0);
const displayRating = hoverRating || rating;
function handleClick(value: number) {
setRating(value);
onChange?.(value);
}
return (
<div
className="flex w-full star-rating"
onMouseLeave={() => setHoverRating(0)}
aria-label="Star rating"
>
{Array.from({ length: maxStars }, (_, index) => {
const value = index + 1;
const filled = value <= displayRating;
return (
<button
key={value}
type="button"
className="star-button"
onClick={() => handleClick(value)}
onMouseEnter={() => setHoverRating(value)}
aria-label={`Rate ${value} out of ${maxStars}`}
aria-pressed={value === rating}
>
<StarIcon filled={filled} />
</button>
);
})}
</div>
);
}