Skip to content
Browse documentation

Whole or half-star ratings with hover previews, rolling values and native radio behaviour for keyboards, forms and screen readers.

Used forProduct reviewsFeedback surveysMarketplacesContent and courses

Install with the shadcn CLI

$ npx shadcn@latest add https://hairlineui.com/r/rating-input.json

Registered the namespace? Then it’s shadcn add @hairline/rating-input. Set it up

Templates

Need the whole page?

61 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 6 are free.

All 61 templates

Where it’s used

  • Product reviews

    Collect a rating beside the review text and submit it with the form.

  • Feedback surveys

    Add a quick scored question with clear selected and empty states.

  • Marketplaces

    Rate sellers, stays or services with half-star precision.

  • Content and courses

    Let members rate a lesson, article or resource in place.

What it handles for you

Ratings often look simple but lose native keyboard behaviour, form values or half-star semantics once custom visuals are added. This keeps native radios under the entire interaction.

Instead of wiring upcustom star buttonsreact-ratingmanual radio-group wiringhalf-star hit targetsrating value and preview state
  1. Native form behaviour

    Real named radio inputs submit the rating and participate in required-field validation.

  2. Whole and half stars

    Half-star mode gives each side of a star its own labelled radio and precise 50% fill.

  3. Preview before choosing

    Pointer and focus previews update the stars and readout without changing the committed form value.

  4. Clear on repeat

    With clearable enabled, choosing the current rating again returns the value to null.

  5. Directional readout

    The number rolls up or down with the preview while the words morph to the matching rating label.

  6. Read-only and disabled

    Read-only preserves the submitted value without editing; disabled uses native disabled controls and reduced emphasis.

Overview

A star rating is a form control, not five clickable SVGs. Native radios underneath provide real arrow-key navigation, validation and form submission while the visual layer adds whole or half-star fills, a lighter preview under the pointer, a fill that runs star to star in the direction the rating moved, a small throw on the star you pick and a rolling numeric readout. Selecting the same rating again can clear it, read-only and disabled states remain distinct, and every value stays an ordinary number or null.

States

empty
Quiet outlined stars and a Not rated label; the radio group has no selected value.
preview
Hover or keyboard focus fills to the proposed rating at half strength and rolls the readout without committing it.
selected
The fill runs star to star, 45ms apart, in the direction the rating moved; the picked star throws to 1.28× and settles.
half
The left and right halves have separate hit areas and radio labels; the fill eases to 50%.
cleared
Choosing the current value again empties the rating and returns the readout to Not rated.

Usage

usage.tsx
import { RatingInput } from "@/components/rating-input";<RatingInput  label="Rate your experience"  name="rating"  value={rating}  onValueChange={setRating}  allowHalf  required/>

Works with

A review form with a real rating value

The native radio group submits with the rest of the form. You can also keep the value in React for validation or a server action.

example.tsx
"use client";import * as React from "react";import { RatingInput } from "@/components/rating-input";export function ReviewForm() {  const [rating, setRating] = React.useState<number | null>(null);  async function submit() {    if (rating === null) return;    await fetch("/api/reviews", {      method: "POST",      body: JSON.stringify({ rating }),    });  }  return (    <RatingInput      label="Overall rating"      name="rating"      value={rating}      onValueChange={setRating}      allowHalf      required      hint="Choose a rating from 0.5 to 5."    />  );}

Props

value / defaultValue
number | null
The committed rating; null means no selection.
onValueChange
(value: number | null) => void
Called for selection and clear-on-repeat.
max= 5
number
Number of stars, clamped from 1 to 10.
allowHalf= false
boolean
Adds half-star values and independent left/right hit targets.
clearable= true
boolean
Clears when the current rating is selected again.
labels
readonly string[]
Words for whole rating levels; numeric text is the fallback.
showValue= true
boolean
Shows the rolling number and rating words.
name
string
Native radio group name used in form submission.
size= "md"
"sm" | "md" | "lg"
Star size: 24px, 29px or 34px.
label / hint / error
ReactNode
Shared field label, help and external error.
required / disabled / readOnly
boolean
Native validation and interaction states.

Accessibility and motion

  • Each rating is a native radio labelled “n out of max”; Arrow keys move through values and Space selects.
  • Pointer and focus previews do not call onValueChange. Escape or pointer leave restores the committed preview.
  • Read-only radios remain in the form but are removed from the tab order; disabled radios use the native disabled attribute.
  • Reduced motion removes star scaling, fill transitions and rolling numbers.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

The CLI also installs Number roll, Text morph.

Source

"use client";import * as React from "react";import { Field, useFieldIds } from "./field";import { NumberRoll } from "./number-roll";import { TextMorph } from "./text-morph";import { EASE_OUT, EASE_THROW, useInteractionReducedMotion } from "./ui-interaction-motion";export interface RatingInputProps {  value?: number | null;  defaultValue?: number | null;  onValueChange?: (value: number | null) => void;  max?: number;  allowHalf?: boolean;  clearable?: boolean;  labels?: readonly string[];  showValue?: boolean;  label?: React.ReactNode;  hint?: React.ReactNode;  error?: React.ReactNode;  required?: boolean;  disabled?: boolean;  readOnly?: boolean;  name?: string;  size?: "sm" | "md" | "lg";  id?: string;  className?: string;}const DEFAULT_LABELS = ["Poor", "Fair", "Good", "Very good", "Excellent"];const clamp = (n: number, min: number, max: number) => Math.min(max, Math.max(min, n));/* * The fill runs star to star in the direction the rating moved (each star waits for the one before it), a hovered or * focused rating is a lighter preview of the same fill, and the star you pick gives one small throw. */const STAGGER = 45;const Star = React.forwardRef<HTMLSpanElement, { fill: number; active: boolean; preview: boolean; delay: number; size: number; reduced: boolean }>(function Star(  { fill, active, preview, delay, size, reduced },  ref,) {  const path = "m12 2.7 2.85 5.78 6.38.93-4.62 4.5 1.09 6.36L12 17.27l-5.7 3 1.09-6.36-4.62-4.5 6.38-.93L12 2.7Z";  return (    <span      ref={ref}      aria-hidden="true"      className="relative block"      style={{ width: size, height: size, transform: active ? "scale(1.08)" : "scale(1)", transition: reduced ? "none" : `transform 340ms ${EASE_THROW}` }}    >      <svg viewBox="0 0 24 24" className="absolute inset-0 size-full" fill="none">        <path d={path} style={{ fill: "color-mix(in oklab, var(--foreground) 4%, transparent)", stroke: "color-mix(in oklab, var(--foreground) 24%, var(--border))" }} strokeWidth="1.35" strokeLinejoin="round" />      </svg>      <span        className="absolute inset-y-0 left-0 overflow-hidden"        style={{          width: `${fill * 100}%`,          opacity: preview ? 0.5 : 1,          transition: reduced ? "none" : `width 260ms ${EASE_OUT} ${delay}ms, opacity 200ms ${EASE_OUT}`,        }}      >        <svg viewBox="0 0 24 24" className="absolute inset-y-0 left-0 h-full max-w-none" style={{ width: size }} fill="none">          <path d={path} fill="var(--primary)" stroke="var(--primary)" strokeWidth="1.35" strokeLinejoin="round" />        </svg>      </span>    </span>  );});export function RatingInput({  value,  defaultValue = null,  onValueChange,  max = 5,  allowHalf = false,  clearable = true,  labels = DEFAULT_LABELS,  showValue = true,  label,  hint,  error,  required,  disabled,  readOnly,  name,  size = "md",  id,  className = "",}: RatingInputProps) {  const reduced = useInteractionReducedMotion();  const ids = useFieldIds(id);  const autoName = React.useId();  const groupName = name ?? autoName;  const [own, setOwn] = React.useState<number | null>(defaultValue);  const [preview, setPreview] = React.useState<number | null>(null);  const count = Math.max(1, Math.min(10, Math.round(max)));  const step = allowHalf ? 0.5 : 1;  const normalise = (next: number | null) => (next === null ? null : clamp(Math.round(next / step) * step, step, count));  const current = normalise(value !== undefined ? value : own);  const shown = preview ?? current ?? 0;  // Where the fill last stood, so the run can start from there and go the way it moved.  const [trail, setTrail] = React.useState({ from: shown, to: shown });  if (trail.to !== shown) setTrail({ from: trail.to, to: shown });  const stars = React.useRef<(HTMLSpanElement | null)[]>([]);  const delayFor = (index: number) => {    const { from, to } = trail;    if (to > from) return index + 1 > from && index < to ? (index - Math.floor(from)) * STAGGER : 0;    if (to < from) return index + 1 > to && index < from ? (Math.ceil(from) - 1 - index) * STAGGER : 0;    return 0;  };  const pixels = size === "sm" ? 24 : size === "lg" ? 34 : 29;  const options = React.useMemo(() => Array.from({ length: count / step }, (_, i) => (i + 1) * step), [count, step]);  const describedBy = [hint && !error ? ids.hint : null, error ? ids.error : null].filter(Boolean).join(" ") || undefined;  const words = shown ? labels[Math.ceil(shown) - 1] ?? `${shown} out of ${count}` : "Not rated";  const commit = (next: number | null) => {    const normalised = normalise(next);    if (value === undefined) setOwn(normalised);    onValueChange?.(normalised);    const star = normalised ? stars.current[Math.ceil(normalised) - 1] : null;    if (star && !reduced) star.animate([{ scale: "1" }, { scale: "1.28" }, { scale: "1" }], { duration: 420, easing: EASE_THROW, composite: "add" });  };  return (    <Field id={ids.id} label={label} hint={hint} error={error} required={required} className={className}>      <div className="flex flex-wrap items-center gap-x-4 gap-y-2 px-1">        <div          role="radiogroup"          aria-label={typeof label === "string" ? label : "Rating"}          aria-describedby={describedBy}          aria-readonly={readOnly || undefined}          onPointerLeave={() => setPreview(null)}          onKeyDown={(e) => {            if (e.key === "Escape") setPreview(null);          }}          className={`flex items-center gap-0.5 ${disabled ? "opacity-50" : ""}`}        >          {Array.from({ length: count }, (_, index) => {            const fill = clamp(shown - index, 0, 1);            return (              <span key={index} className="relative" style={{ width: pixels, height: pixels }}>                {options.filter((option) => Math.ceil(option) === index + 1).map((option) => {                  const half = allowHalf && option % 1 !== 0;                  return (                    <label                      key={option}                      className={`absolute inset-y-0 z-10 ${half ? "left-0 w-1/2" : allowHalf ? "right-0 w-1/2" : "inset-x-0"} ${disabled || readOnly ? "cursor-default" : "cursor-pointer"}`}                      onPointerEnter={() => {                        if (!disabled && !readOnly) setPreview(option);                      }}                    >                      <input                        id={option === step ? ids.id : undefined}                        type="radio"                        name={groupName}                        value={option}                        checked={current === option}                        required={required}                        disabled={disabled}                        tabIndex={readOnly ? -1 : undefined}                        aria-label={`${option} out of ${count}`}                        className="peer absolute inset-0 m-0 size-full cursor-[inherit] opacity-0 outline-none"                        onFocus={() => {                          if (!readOnly) setPreview(option);                        }}                        onBlur={() => setPreview(null)}                        onChange={() => {                          if (!readOnly) commit(option);                        }}                        onClick={(e) => {                          if (readOnly) {                            e.preventDefault();                            return;                          }                          if (clearable && current === option) {                            commit(null);                            setPreview(null);                          }                        }}                      />                      <span className="pointer-events-none absolute inset-0 rounded-full peer-focus-visible:shadow-[0_0_0_2px_var(--background),0_0_0_4px_var(--ring)]" aria-hidden="true" />                    </label>                  );                })}                <Star                  ref={(el) => {                    stars.current[index] = el;                  }}                  fill={fill}                  active={Math.ceil(shown) === index + 1 && shown > 0}                  preview={preview !== null && preview !== current}                  delay={reduced ? 0 : delayFor(index)}                  size={pixels}                  reduced={reduced}                />              </span>            );          })}        </div>        {showValue && (          // The readout keeps the width of its widest number and words (laid out invisibly in the same cell), so a          // hover that changes "Fair" to "Excellent" never moves the stars.          <div aria-hidden="true" className="flex min-w-0 items-baseline gap-2">            <span className="inline-grid text-[13px] font-medium tabular-nums text-foreground">              <span className="invisible [grid-area:1/1]">                {allowHalf ? `${count - 1}.5` : count}                <span className="text-[11.5px] font-normal">/{count}</span>              </span>              <span className="[grid-area:1/1]">                <NumberRoll value={shown} format={{ maximumFractionDigits: allowHalf ? 1 : 0 }} duration={420} />                <span className="text-[11.5px] font-normal text-muted-foreground">/{count}</span>              </span>            </span>            <span className="inline-grid text-[12px] text-muted-foreground">              {[...labels.slice(0, count), "Not rated"].map((word) => (                <span key={word} className="invisible whitespace-nowrap [grid-area:1/1]">                  {word}                </span>              ))}              <span className="whitespace-nowrap [grid-area:1/1]">                <TextMorph animateWidth={false}>{words}</TextMorph>              </span>            </span>          </div>        )}      </div>    </Field>  );}export default RatingInput;

Registry item: /r/rating-input.json