"use client";
// src/components/StarRating/StarRating.tsx
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useId, useRef, useState, type KeyboardEvent, type PointerEvent } from "react";
type StarRatingProps = {
/** Controlled value. Leave out to let the component keep its own value */
value?: number;
/** Starting value when uncontrolled */
defaultValue?: number;
onChange?: (value: number) => void;
/** Number of stars */
max?: number;
/** Allow half stars like 3.5 */
allowHalf?: boolean;
/** Click the same rating again to clear it */
allowClear?: boolean;
/** Just show the rating (works with decimals like 4.3) */
readOnly?: boolean;
/** Star size in px */
size?: number;
/** Filled star color */
color?: string;
/** Words shown for each whole rating. Pass [] to hide */
labels?: string[];
/** Shown next to the stars in read-only mode, e.g. "(1,284 reviews)" */
caption?: string;
/** Read by screen readers */
ariaLabel?: string;
disabled?: boolean;
className?: string;
};
const DEFAULT_LABELS = ["Terrible", "Bad", "Okay", "Good", "Amazing"];
// 24 x 24 star with soft rounded points
const STAR =
"M11.05 2.93a1.05 1.05 0 0 1 1.9 0l2.3 4.67 5.15.75a1.05 1.05 0 0 1 .58 1.8l-3.72 3.63.88 5.13a1.05 1.05 0 0 1-1.53 1.11L12 17.6l-4.61 2.42a1.05 1.05 0 0 1-1.53-1.1l.88-5.14-3.72-3.63a1.05 1.05 0 0 1 .58-1.8l5.15-.75z";
// Burst dots around the picked star: angle in degrees
const BURST = [0, 60, 120, 180, 240, 300];
export function StarRating({
value,
defaultValue = 0,
onChange,
max = 5,
allowHalf = false,
allowClear = true,
readOnly = false,
size = 32,
color = "#F59E0B",
labels = DEFAULT_LABELS,
caption,
ariaLabel = "Rating",
disabled = false,
className = "",
}: StarRatingProps) {
const reduce = useReducedMotion();
const uid = useId().replace(/:/g, "");
const rowRef = useRef<HTMLDivElement>(null);
const [inner, setInner] = useState(defaultValue);
const [hover, setHover] = useState<number | null>(null);
// Changes on every pick, to replay the pop and burst
const [pickKey, setPickKey] = useState(0);
const rating = value ?? inner;
const interactive = !readOnly && !disabled;
const shown = interactive && hover !== null ? hover : rating;
const step = allowHalf ? 0.5 : 1;
const commit = (next: number) => {
const clamped = Math.min(max, Math.max(0, next));
if (value === undefined) setInner(clamped);
onChange?.(clamped);
if (clamped > 0) setPickKey((k) => k + 1);
};
// Which rating the pointer is on: whole stars, or halves if allowed
const valueAt = (e: PointerEvent<HTMLDivElement>) => {
const rect = rowRef.current!.getBoundingClientRect();
const x = Math.min(Math.max(e.clientX - rect.left, 0), rect.width - 1);
const raw = (x / rect.width) * max;
const v = allowHalf ? Math.floor(raw * 2) / 2 + 0.5 : Math.floor(raw) + 1;
return Math.min(max, v);
};
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
const keys: Record<string, number> = {
ArrowRight: rating + step,
ArrowUp: rating + step,
ArrowLeft: rating - step,
ArrowDown: rating - step,
Home: 0,
End: max,
};
if (e.key in keys) {
e.preventDefault();
commit(keys[e.key]);
} else if (/^[0-9]$/.test(e.key) && Number(e.key) <= max) {
e.preventDefault();
commit(Number(e.key));
}
};
const word = labels.length ? labels[Math.ceil(shown) - 1] : undefined;
const valueText = `${rating} out of ${max}${rating && labels.length ? `, ${labels[Math.ceil(rating) - 1] ?? ""}` : ""}`;
return (
<div className={`inline-flex flex-wrap items-center gap-x-3 gap-y-1 ${className}`}>
<div
ref={rowRef}
role={readOnly ? "img" : "slider"}
aria-label={readOnly ? `${ariaLabel}: ${rating} out of ${max}` : ariaLabel}
aria-valuemin={readOnly ? undefined : 0}
aria-valuemax={readOnly ? undefined : max}
aria-valuenow={readOnly ? undefined : rating}
aria-valuetext={readOnly ? undefined : valueText}
aria-disabled={disabled || undefined}
tabIndex={interactive ? 0 : undefined}
onKeyDown={interactive ? onKeyDown : undefined}
onPointerMove={interactive ? (e) => setHover(valueAt(e)) : undefined}
onPointerLeave={interactive ? () => setHover(null) : undefined}
onPointerDown={
interactive
? (e) => {
// Touch: show the preview right away
if (e.pointerType !== "mouse") setHover(valueAt(e));
}
: undefined
}
onClick={
interactive
? (e) => {
const v = valueAt(e as unknown as PointerEvent<HTMLDivElement>);
commit(allowClear && v === rating ? 0 : v);
if ((e as unknown as PointerEvent).pointerType !== "mouse") setHover(null);
}
: undefined
}
className={`relative flex touch-none rounded-lg outline-offset-4 select-none focus-visible:outline-2 ${interactive ? "cursor-pointer" : ""} ${disabled ? "opacity-50" : ""}`}
style={{ outlineColor: color, gap: size * 0.12 }}
>
{Array.from({ length: max }, (_, i) => {
// 0 = empty, 0.5 = half, 1 = full (decimals work in read-only mode)
const fill = Math.min(1, Math.max(0, shown - i));
const isPicked = interactive && hover === null && Math.ceil(rating) === i + 1;
return (
<motion.div
key={isPicked ? `${i}-${pickKey}` : i}
className="relative shrink-0"
style={{ width: size, height: size }}
// Stars grow a little as the hover passes over them
animate={
reduce
? {}
: isPicked && pickKey > 0
? { scale: [1, 1.35, 0.95, 1], rotate: [0, -12, 6, 0] }
: { scale: interactive && hover !== null && fill > 0 ? 1.08 : 1, rotate: 0 }
}
transition={
isPicked && pickKey > 0
? { duration: 0.5, ease: "easeOut" }
: { type: "spring", stiffness: 400, damping: 20, delay: hover !== null ? i * 0.02 : 0 }
}
>
<svg viewBox="0 0 24 24" className="size-full overflow-visible" aria-hidden="true">
<defs>
<clipPath id={`fill-${uid}-${i}`}>
<motion.rect
x={0}
y={0}
height={24}
initial={false}
animate={{ width: fill * 24 }}
transition={reduce ? { duration: 0 } : { type: "spring", stiffness: 500, damping: 35 }}
/>
</clipPath>
</defs>
{/* Empty star */}
<path d={STAR} className="fill-neutral-200 dark:fill-neutral-700" />
{/* Filled part */}
<path d={STAR} fill={color} clipPath={`url(#fill-${uid}-${i})`} />
{/* Small shine on filled stars */}
{fill > 0 && <path d="M9.2 8.6l1.2-2.4" stroke="#fff" strokeOpacity={0.55} strokeWidth={1.4} strokeLinecap="round" />}
</svg>
{/* Burst when this star is picked */}
{!reduce && (
<AnimatePresence>
{isPicked && pickKey > 0 && (
<span key={pickKey} className="pointer-events-none absolute inset-0" aria-hidden="true">
{BURST.map((deg) => {
const a = (deg * Math.PI) / 180;
return (
<motion.span
key={deg}
className="absolute top-1/2 left-1/2 size-1.5 -translate-1/2 rounded-full"
style={{ background: color }}
initial={{ x: 0, y: 0, opacity: 1, scale: 1 }}
animate={{ x: Math.cos(a) * size * 0.85, y: Math.sin(a) * size * 0.85, opacity: 0, scale: 0.3 }}
transition={{ duration: 0.55, ease: "easeOut" }}
/>
);
})}
</span>
)}
</AnimatePresence>
)}
</motion.div>
);
})}
</div>
{/* Feeling word (interactive) or number + caption (read-only) */}
{readOnly ? (
<span className="text-sm text-neutral-600 tabular-nums dark:text-neutral-400" aria-hidden="true">
<span className="font-semibold text-neutral-900 dark:text-white">{rating.toFixed(1)}</span>
{caption && <span className="ml-1">{caption}</span>}
</span>
) : (
labels.length > 0 && (
<span className="relative block h-6 min-w-20 overflow-hidden text-sm font-medium" aria-hidden="true">
<AnimatePresence mode="popLayout" initial={false}>
{word && (
<motion.span
key={word}
className="absolute inset-0 whitespace-nowrap"
style={{ color: hover !== null ? undefined : color }}
initial={reduce ? { opacity: 0 } : { y: 16, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
exit={reduce ? { opacity: 0 } : { y: -16, opacity: 0 }}
transition={{ duration: 0.18 }}
>
<span className={hover !== null ? "text-neutral-600 dark:text-neutral-300" : ""}>{word}</span>
</motion.span>
)}
</AnimatePresence>
</span>
)
)}
</div>
);
}
export default StarRating;
// Component Source: https://codekk.devComponent details
Overview, install command, dependencies, and project links.
An animated star rating component for React built with TypeScript, Motion, SVG, and Tailwind CSS v4. It's made for product reviews, feedback forms, order and delivery ratings, course and movie ratings, and testimonial sections. When you move over the stars, they fill up to where your pointer is and grow a little, one after another, so you can see the rating before you pick it. A feeling word next to the stars (Terrible, Bad, Okay, Good, Amazing) slides in as you move. When you click, the picked star pops with a small twist and a burst of dots flies out around it. Clicking the same rating again clears it. With allowHalf, each star is split in two, so people can rate 3.5 or 4.5, and the fill moves smoothly with a spring. The readOnly mode shows any rating, even decimals like 4.3, with the exact part of the last star filled, plus the number and a caption like "(1,284 reviews)". This makes it easy to use for both giving and showing ratings. The number of stars, size, color, and feeling words can all be changed, and you can hide the words with labels={[]}. It works as a controlled or uncontrolled component. On phones, tapping shows the preview and picks the rating in one touch. It works with the keyboard too: the arrow keys move up and down, Home and End jump to 0 and full, and number keys pick a rating right away. For screen readers, the interactive rating is a slider with a clear value like "4 out of 5, Good", and the read-only rating is read as one image label. Dark mode styles are included. Each star uses React's useId, so many ratings can share one page. When prefers-reduced-motion is enabled, the grow, pop, burst, and sliding words are turned off. "use client" is included, so it works in Vite, Create React App, and Next.js.
Install
npm create vite@latest my-app -- --template react-ts cd my-app npm install motionDependencies
Discussion
Feedback, implementation tips, and usage notes.
Comments
Sign in to join the conversation
Similar Components
More from the same category


