Rating
An accessible React star rating component built with Tailwind CSS and Motion: hover to preview, click or use the arrow keys to rate, half-star steps, and a small pop as the stars fill. Read-only mode fills fractional averages precisely, any lucide icon, count, size or color works, and a hidden input submits the value with your form.
- Hover preview
- Half stars
- Pop on select
- Read-only averages
- Custom icons
- Form-ready
- Slider a11y
"use client";
import * as React from "react";
import { Rating } from "@/components/dusk/rating/rating";
const words = ["Not rated", "Terrible", "Meh", "Good", "Great", "Loved it"];
export default function RatingDemo() {
const [value, setValue] = React.useState(4);
return (
<div className="flex flex-col items-center gap-3">
<p aria-hidden className="text-sm font-medium">How was your stay?</p>
<Rating value={value} onValueChange={setValue} size="lg" label="How was your stay?" />
<p className="h-5 text-sm text-muted-foreground" aria-hidden>
{words[Math.ceil(value)]}
</p>
</div>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/rating.json1. Install the dependencies.
npm install motion lucide-react2. Copy the source into
components/dusk/rating/rating.tsx.rating.tsx "use client"; import * as React from "react"; import { motion, useReducedMotion } from "motion/react"; import { Star, type LucideProps } from "lucide-react"; import { cn } from "@/lib/utils"; const sizes = { sm: 18, md: 24, lg: 32 } as const; export interface RatingProps extends Omit<React.ComponentProps<"div">, "children" | "defaultValue" | "onChange" | "role"> { value?: number; defaultValue?: number; onValueChange?: (value: number) => void; /** Number of icons. */ count?: number; /** Allow half steps (3.5). */ allowHalf?: boolean; /** Display only. Fractions like 4.3 fill precisely. */ readOnly?: boolean; disabled?: boolean; /** Clicking the current value again resets to 0. */ clearable?: boolean; /** Icon size: a preset or pixels. */ size?: keyof typeof sizes | number; /** Fill color (any CSS color). Defaults to the primary mint. */ color?: string; /** Any lucide icon (or component taking className, fill, strokeWidth). */ icon?: React.ComponentType<LucideProps>; /** Name for a hidden input, so the value is submitted with a form. */ name?: string; /** Accessible name, e.g. "Rate your stay". */ label?: string; /** Text read for a value. Defaults to "3.5 out of 5 stars". */ getValueText?: (value: number, count: number) => string; } const clamp = (value: number, max: number) => Math.min(max, Math.max(0, value)); /** * A star rating input with hover preview, half steps and a small pop as stars fill, exposed as a keyboard-friendly slider that also submits with forms. */ export function Rating({ value: valueProp, defaultValue = 0, onValueChange, count = 5, allowHalf = false, readOnly = false, disabled = false, clearable = true, size = "md", color, icon: Icon = Star, name, label = "Rating", getValueText = (v, max) => `${v} out of ${max} star${max === 1 ? "" : "s"}`, className, style, onKeyDown, ...props }: RatingProps) { const reduceMotion = useReducedMotion(); const [uncontrolled, setUncontrolled] = React.useState(defaultValue); const [hover, setHover] = React.useState<number | null>(null); // Bumped on every pick so the filled stars replay their pop. const [pop, setPop] = React.useState(0); const value = clamp(valueProp ?? uncontrolled, count); const step = allowHalf ? 0.5 : 1; const interactive = !readOnly && !disabled; const display = interactive && hover !== null ? hover : value; const px = typeof size === "number" ? size : sizes[size]; const rootStyle = { "--rating-color": color ?? "var(--color-primary)", ...style } as React.CSSProperties; const commit = (next: number) => { const snapped = clamp(Math.round(next / step) * step, count); if (valueProp === undefined) setUncontrolled(snapped); if (snapped > 0) setPop((p) => p + 1); onValueChange?.(snapped); }; const valueAt = (event: React.MouseEvent<HTMLElement>, index: number) => { if (!allowHalf) return index + 1; const rect = event.currentTarget.getBoundingClientRect(); return event.clientX - rect.left < rect.width / 2 ? index + 0.5 : index + 1; }; const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => { onKeyDown?.(event); if (!interactive || event.defaultPrevented) return; let next: number | null = null; if (event.key === "ArrowRight" || event.key === "ArrowUp") next = value + step; else if (event.key === "ArrowLeft" || event.key === "ArrowDown") next = value - step; else if (event.key === "Home") next = 0; else if (event.key === "End") next = count; else if (/^[0-9]$/.test(event.key) && Number(event.key) <= count) next = Number(event.key); if (next === null) return; event.preventDefault(); if (clamp(next, count) !== value) commit(next); }; const stars = Array.from({ length: count }, (_, index) => { const fill = clamp(display - index, 1); const filled = value >= index + step - 0.001; const previewing = interactive && hover !== null; return ( <span key={index} aria-hidden data-star={index} className={cn("relative grid shrink-0 place-items-center", interactive && "cursor-pointer")} style={{ width: px, height: px }} onPointerMove={interactive ? (event) => event.pointerType === "mouse" && setHover(valueAt(event, index)) : undefined} onClick={ interactive ? (event) => { const next = valueAt(event, index); commit(clearable && next === value ? 0 : next); } : undefined } > <motion.span key={filled ? pop : "idle"} className="relative grid size-full place-items-center" initial={pop === 0 || !filled || reduceMotion ? false : { scale: 0.85 }} animate={{ scale: 1 }} transition={{ type: "spring", bounce: 0.15, duration: 0.25, delay: reduceMotion ? 0 : index * 0.03 }} > <Icon className="absolute size-full text-muted-foreground/50" strokeWidth={1.5} /> <span className={cn( "absolute inset-0 grid place-items-center", "transition-[clip-path,opacity] duration-150 ease-out motion-reduce:transition-none", "text-(--rating-color)", previewing && "opacity-70" )} style={{ clipPath: `inset(0 ${100 - fill * 100}% 0 0)` }} > <Icon className="size-full" fill="currentColor" strokeWidth={1.5} /> </span> </motion.span> </span> ); }); if (readOnly) { return ( <div role="img" aria-label={`${label}: ${getValueText(value, count)}`} data-slot="rating" data-readonly="" className={cn("inline-flex items-center gap-1", disabled && "opacity-50", className)} style={rootStyle} {...props} > {stars} {name ? <input type="hidden" name={name} value={value} /> : null} </div> ); } return ( <div role="slider" tabIndex={disabled ? -1 : 0} aria-label={label} aria-valuemin={0} aria-valuemax={count} aria-valuenow={value} aria-valuetext={getValueText(value, count)} aria-disabled={disabled || undefined} data-slot="rating" className={cn( "inline-flex items-center gap-1 rounded-md outline-none select-none", "focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:ring-offset-4 focus-visible:ring-offset-background", disabled && "pointer-events-none opacity-50", className )} style={rootStyle} onKeyDown={handleKeyDown} onPointerLeave={() => setHover(null)} {...props} > {stars} {name ? <input type="hidden" name={name} value={value} /> : null} </div> ); }
Usage
"use client"
import * as React from "react"
import { Rating } from "@/components/dusk/rating/rating"
export function Review() {
const [stars, setStars] = React.useState(0)
return <Rating value={stars} onValueChange={setStars} label="Rate this product" />
}Examples
Half stars & read-only
allowHalf picks the left or right half of each star. With readOnly any fraction — like an average of 4.7 — fills to the exact width.
Your rating
3.5 / 5
Aurora Hotel
4.7 · 1,284Harbor Loft
4.2 · 312Cedar Cabin
3.6 · 89
"use client";
import * as React from "react";
import { Rating } from "@/components/dusk/rating/rating";
const reviews = [
{ name: "Aurora Hotel", score: 4.7, count: 1284 },
{ name: "Harbor Loft", score: 4.2, count: 312 },
{ name: "Cedar Cabin", score: 3.6, count: 89 },
];
export default function RatingHalfDemo() {
const [value, setValue] = React.useState(3.5);
return (
<div className="grid w-full max-w-md gap-6 sm:grid-cols-2">
<div className="space-y-2">
<p className="text-sm font-medium">Your rating</p>
<Rating value={value} onValueChange={setValue} allowHalf label="Your rating" />
<p className="text-xs text-muted-foreground tabular-nums">{value.toFixed(1)} / 5</p>
</div>
<ul className="space-y-3">
{reviews.map((r) => (
<li key={r.name} className="space-y-1">
<p className="text-sm">{r.name}</p>
<div className="flex items-center gap-2">
<Rating value={r.score} readOnly size="sm" label={r.name} />
<span className="text-xs text-muted-foreground tabular-nums">
{r.score} · {r.count.toLocaleString("en-US")}
</span>
</div>
</li>
))}
</ul>
</div>
);
}Icons, count, size & color
Pass any lucide icon to icon, change count, set size to a preset or pixels, and tint it with color. getValueText customises what screen readers hear.
"use client";
import { Flame, Heart, Zap } from "lucide-react";
import { Rating } from "@/components/dusk/rating/rating";
export default function RatingCustomDemo() {
return (
<div className="flex flex-col items-start gap-5">
<div className="flex flex-col items-start gap-1.5 sm:flex-row sm:items-center sm:gap-4">
<span className="w-20 text-sm text-muted-foreground">Hearts</span>
<Rating icon={Heart} defaultValue={3} label="Hearts" color="#f472b6" />
</div>
<div className="flex flex-col items-start gap-1.5 sm:flex-row sm:items-center sm:gap-4">
<span className="w-20 text-sm text-muted-foreground">Energy</span>
<Rating icon={Zap} count={10} size="sm" defaultValue={7} label="Energy level" />
</div>
<div className="flex flex-col items-start gap-1.5 sm:flex-row sm:items-center sm:gap-4">
<span className="w-20 text-sm text-muted-foreground">Spice</span>
<Rating
icon={Flame}
count={3}
size={36}
defaultValue={2}
label="Spice level"
getValueText={(v) => ["No spice", "Mild", "Hot", "Extra hot"][v]}
/>
</div>
</div>
);
}In a form
Give it a name and the value is submitted through a hidden input, so it works with FormData and server actions.
"use client";
import * as React from "react";
import { Rating } from "@/components/dusk/rating/rating";
import { Button } from "@/components/ui/button";
export default function RatingFormDemo() {
const [submitted, setSubmitted] = React.useState<string | null>(null);
return (
<form
className="flex w-full max-w-xs flex-col gap-4 rounded-xl border bg-card p-5"
onSubmit={(event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
setSubmitted(JSON.stringify(Object.fromEntries(data)));
}}
>
<div className="space-y-2">
<p className="text-sm font-medium">Food</p>
<Rating name="food" defaultValue={4} label="Food" />
</div>
<div className="space-y-2">
<p className="text-sm font-medium">Service</p>
<Rating name="service" allowHalf defaultValue={3.5} label="Service" />
</div>
<Button type="submit" size="sm">Submit review</Button>
<output aria-live="polite" className="min-h-4 font-mono text-xs text-muted-foreground">
{submitted}
</output>
</form>
);
}API Reference
Also accepts any div attribute.
| Prop | Type | Default | Description |
|---|---|---|---|
| value | number | — | Controlled value. |
| defaultValue | number | 0 | Starting value when uncontrolled. |
| onValueChange | (value: number) => void | — | Called when the user picks a value. |
| count | number | 5 | Number of icons. |
| allowHalf | boolean | false | Allow 0.5 steps. |
| readOnly | boolean | false | Display only; renders as an image with a spoken value. |
| disabled | boolean | false | Dims the rating and removes it from the tab order. |
| clearable | boolean | true | Clicking the current value again resets to 0. |
| size | "sm" | "md" | "lg" | number | "md" | Icon size preset (18 / 24 / 32px) or pixels. |
| color | string | var(--color-primary) | Fill color. |
| icon | ComponentType<LucideProps> | Star | Icon to render. |
| name | string | — | Renders a hidden input with this name. |
| label | string | "Rating" | Accessible name. |
| getValueText | (value, count) => string | "3 out of 5 stars" | Spoken value text. |
Accessibility
- Interactive ratings are a single focusable
role="slider"witharia-valuenow,aria-valuemaxand value text like “3.5 out of 5 stars”. - Arrow keys change the value by one step (half a star with allowHalf), Home clears it, End fills every star, and number keys jump straight to a value.
- Read-only ratings render as
role="img"with a label such as “Aurora Hotel: 4.7 out of 5 stars”, so averages are read once instead of star by star. - The icons are decorative and hidden from assistive technology.
- Hover preview is mouse-only; touch taps set the value directly.
- With prefers-reduced-motion the pop and fill transitions are skipped.