Overview

A rating control with some delight. Hovering previews the score: the star under the pointer lifts and tilts, and the ones before it brighten. Choosing a rating pops the stars in sequence and sends a small burst from the last one. Half stars fill with a clean clip, labels adds a word under the stars that swaps with a blur, and clearable lets a second click reset it. It's a slider for assistive tech, with arrow keys, Home, End and the number keys.


Installation

Use the CLI to install the component automatically:

$ pnpm dlx shadcn@latest add https://ui.sanjid.in/r/star-rating.json

Install dependencies:

$ pnpm add motion lucide-react

Add the utility function for class merging:

lib/utils.ts
tsx
import { ClassValue, clsx } from "clsx";import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {  return twMerge(clsx(inputs));}

Copy the component code into your project:

components/ui/star-rating.tsx
tsx
"use client";
import React, { useCallback, useEffect, useState } from "react";import { AnimatePresence, motion, useReducedMotion } from "motion/react";import { cn } from "@/lib/utils";
export type StarRatingProps = {  value?: number;  defaultValue?: number;  onChange?: (value: number) => void;  max?: number;  /** Allow half stars (pointer position and arrow keys step by 0.5). */  allowHalf?: boolean;  /** Clicking the current rating again clears it. */  clearable?: boolean;  readOnly?: boolean;  size?: "sm" | "md" | "lg";  /** One label per whole star, e.g. ["Bad", "Meh", "Okay", "Good", "Great"]. Shown under the stars. */  labels?: string[];  className?: string;  "aria-label"?: string;};
const STAR_PATH =  "M12 2.6l2.83 5.9 6.47.8-4.76 4.47 1.22 6.43L12 17.07l-5.76 3.13 1.22-6.43L2.7 9.3l6.47-.8L12 2.6z";const SIZES = { sm: 18, md: 26, lg: 34 };
function useFinePointer() {  const [fine, setFine] = useState(false);  useEffect(() => {    const mq = window.matchMedia("(hover: hover) and (pointer: fine)");    const sync = () => setFine(mq.matches);    sync();    mq.addEventListener("change", sync);    return () => mq.removeEventListener("change", sync);  }, []);  return fine;}
function Burst({ size }: { size: number }) {  return (    <span aria-hidden className="pointer-events-none absolute inset-0">      {Array.from({ length: 7 }, (_, i) => {        const angle = (i / 7) * Math.PI * 2 - Math.PI / 2;        const r = size * 0.85;        return (          <motion.span            key={i}            className="absolute top-1/2 left-1/2 size-1 rounded-full bg-(--star-fill)"            initial={{ x: "-50%", y: "-50%", opacity: 1, scale: 1 }}            animate={{              x: `calc(-50% + ${Math.cos(angle) * r}px)`,              y: `calc(-50% + ${Math.sin(angle) * r}px)`,              opacity: 0,              scale: 0.4,            }}            transition={{ duration: 0.55, ease: [0.23, 1, 0.32, 1] }}          />        );      })}    </span>  );}
export function StarRating({  value: valueProp,  defaultValue = 0,  onChange,  max = 5,  allowHalf = false,  clearable = false,  readOnly = false,  size = "md",  labels,  className,  "aria-label": ariaLabel = "Rating",}: StarRatingProps) {  const reduce = !!useReducedMotion();  const fine = useFinePointer();  const count = Number.isFinite(max) ? Math.max(1, Math.floor(max)) : 5;  const step = allowHalf ? 0.5 : 1;  const isControlled = valueProp !== undefined;  const [uncontrolled, setUncontrolled] = useState(defaultValue);  const value = Math.min(count, Math.max(0, isControlled ? valueProp : uncontrolled));  const [hover, setHover] = useState<number | null>(null);  const [commit, setCommit] = useState<{ value: number; token: number } | null>(null);  const px = SIZES[size];
  const shown = !readOnly && hover !== null ? hover : value;  const labelFor = (v: number) => (labels && v > 0 ? labels[Math.ceil(v) - 1] : undefined);
  const setValue = useCallback(    (next: number) => {      if (readOnly) return;      const bounded = Math.min(count, Math.max(0, Math.round(next / step) * step));      const final = clearable && bounded === value ? 0 : bounded;      if (!isControlled) setUncontrolled(final);      onChange?.(final);      setCommit(final > 0 ? { value: final, token: Date.now() } : null);    },    [clearable, count, isControlled, onChange, readOnly, step, value],  );
  const valueAt = (e: { target: EventTarget; clientX: number }) => {    const star = (e.target as Element).closest<HTMLElement>("[data-star]");    if (!star) return null;    const n = Number(star.dataset.star);    if (!allowHalf) return n;    const r = star.getBoundingClientRect();    return e.clientX - r.left < r.width / 2 ? n - 0.5 : n;  };
  const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {    if (readOnly) return;    let next: number | null = null;    if (e.key === "ArrowRight" || e.key === "ArrowUp") next = Math.min(count, value + step);    else if (e.key === "ArrowLeft" || e.key === "ArrowDown") next = Math.max(step, value - step);    else if (e.key === "Home") next = step;    else if (e.key === "End") next = count;    else if (/^[1-9]$/.test(e.key) && Number(e.key) <= count) next = Number(e.key);    if (next === null) return;    e.preventDefault();    if (next !== value) setValue(next);  };
  const text = `${value} of ${count} stars${labelFor(value) ? `, ${labelFor(value)}` : ""}`;
  return (    <div className={cn("inline-flex flex-col items-center gap-2 [--star-fill:#f5b301]", className)}>      <div        role={readOnly ? "img" : "slider"}        aria-label={readOnly ? `${ariaLabel}: ${text}` : ariaLabel}        aria-valuemin={readOnly ? undefined : 0}        aria-valuemax={readOnly ? undefined : count}        aria-valuenow={readOnly ? undefined : value}        aria-valuetext={readOnly ? undefined : text}        tabIndex={readOnly ? undefined : 0}        onKeyDown={onKeyDown}        onPointerMove={(e) => {          if (readOnly || !fine) return;          const v = valueAt(e);          if (v !== null) setHover(v);        }}        onPointerLeave={() => setHover(null)}        onClick={(e) => {          const v = valueAt(e);          if (v !== null) setValue(v);        }}        className={cn(          "inline-flex items-center rounded-[10px] outline-none",          "focus-visible:ring-2 focus-visible:ring-(--color-focus) focus-visible:ring-offset-4 focus-visible:ring-offset-(--color-paper)",          readOnly ? "cursor-default" : "cursor-pointer",        )}        style={{ gap: px * 0.12 }}      >        {Array.from({ length: count }, (_, i) => {          const n = i + 1;          const fill = Math.min(1, Math.max(0, shown - i));          const hovered = hover !== null && Math.ceil(hover) === n;          const lit = fill > 0;          const popped = commit && !reduce && n <= Math.ceil(commit.value);          return (            <motion.span              key={`${n}-${popped ? commit.token : 0}`}              data-star={n}              className="relative block"              style={{ width: px, height: px }}              initial={popped ? { scale: 0.6 } : false}              animate={{                scale: hovered && !reduce ? 1.18 : lit && hover !== null && !reduce ? 1.06 : 1,                y: hovered && !reduce ? -2 : 0,                rotate: hovered && !reduce ? -6 : 0,              }}              transition={                popped                  ? { type: "spring", bounce: 0.6, duration: 0.5, delay: i * 0.05 }                  : { type: "spring", bounce: 0.4, duration: 0.35 }              }            >              {/* Empty star */}              <svg viewBox="0 0 24 24" className="absolute inset-0 size-full" aria-hidden>                <path                  d={STAR_PATH}                  fill="var(--color-paper-2)"                  stroke="var(--color-rule)"                  strokeWidth="1.5"                  strokeLinejoin="round"                />              </svg>              {/* Filled star, clipped to the fill fraction */}              <span                className="absolute inset-0 transition-[clip-path] duration-200 ease-out"                style={{ clipPath: `inset(0 ${(1 - fill) * 100}% 0 0)` }}              >                <svg viewBox="0 0 24 24" className="size-full drop-shadow-[0_1px_2px_rgba(245,179,1,0.35)]" aria-hidden>                  <path d={STAR_PATH} fill="var(--star-fill)" stroke="var(--star-fill)" strokeWidth="1.5" strokeLinejoin="round" />                  <path d={STAR_PATH} fill="url(#star-sheen)" opacity="0.5" />                  <defs>                    <linearGradient id="star-sheen" x1="0" y1="0" x2="0" y2="1">                      <stop offset="0" stopColor="#fff" stopOpacity="0.7" />                      <stop offset="0.55" stopColor="#fff" stopOpacity="0" />                    </linearGradient>                  </defs>                </svg>              </span>              {popped && n === Math.ceil(commit.value) ? <Burst key={commit.token} size={px} /> : null}            </motion.span>          );        })}      </div>
      {labels ? (        <div className="relative h-5 min-w-24 text-center text-[13px] font-medium text-(--color-ink-2)" aria-hidden>          <AnimatePresence initial={false} mode="popLayout">            <motion.span              key={labelFor(shown) ?? "none"}              initial={reduce ? { opacity: 0 } : { opacity: 0, y: 6, filter: "blur(4px)" }}              animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}              exit={reduce ? { opacity: 0 } : { opacity: 0, y: -6, filter: "blur(4px)" }}              transition={{ duration: 0.22, ease: [0.23, 1, 0.32, 1] }}              className={cn("inline-block", !labelFor(shown) && "text-(--color-neutral)")}            >              {labelFor(shown) ?? (readOnly ? "No rating" : "Tap to rate")}            </motion.span>          </AnimatePresence>        </div>      ) : null}    </div>  );}

Adjust import paths according to your folder structure.


Basic Usage

tsx
import { StarRating } from "@/components/ui/star-rating";
<StarRating  value={score}  onChange={setScore}  size="lg"  clearable  labels={["Rough", "Meh", "Okay", "Good", "Loved it"]}  aria-label="Rate this session"/>
// Display only, with half stars<StarRating value={4.5} readOnly allowHalf size="sm" aria-label="Average" />

Props

PropTypeRequiredDefaultDescription
value / defaultValuenumberNo0Controlled or initial rating.
onChange(value: number) => voidNo—Fires with the new rating (0 when cleared).
maxnumberNo5Number of stars.
allowHalfbooleanNofalseHalf-star steps from the pointer position and arrow keys.
clearablebooleanNofalseChoosing the current rating again resets it to 0.
labelsstring[]No—One word per star, shown under the stars and included in the spoken value.
size"sm" | "md" | "lg"No"md"Star size: 18, 26 or 34px.
readOnlybooleanNofalseDisplay only; exposed as an image with the rating in its label.
aria-label / classNamestringNo—Accessible name, and wrapper classes. Set --star-fill on className to change the star colour.

Best Practices

  1. Add labels so a rating means something specific; they're also read out to screen readers.
  2. Use allowHalf for displaying averages, and whole stars for asking people to rate.
  3. Recolour with a CSS variable, e.g. className="[--star-fill:var(--color-ink)]" for a monochrome look.
  4. Reduced motion keeps the fill and colour but drops the pop, tilt and burst.