View as Markdown

Shadcn Rating

A star rating input for reviews and feedback. It supports half stars, a hover preview, read-only averages such as 4.3, custom icons and native form submission. Each score is a real radio input, so it works with the keyboard and screen readers out of the box.

Installation

npx shadcn@latest add @shadcnuikit/rating1

This adds components/ui/rating.tsx and a demo file. Set up the registry once as described in Shadcn CLI. Rating is free and installs without an API key.

Manual installation

Install the dependencies:

npm install @ui-sdk/react@beta class-variance-authority lucide-react

Copy the source into components/ui/rating.tsx:

components/ui/rating.tsx
"use client";
import * as React from "react";import { Rating as RatingPrimitive, RatingItem as RatingItemPrimitive, createRatingController,} from "@ui-sdk/react/rating";import { cva, type VariantProps } from "class-variance-authority";import { StarIcon, type LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";
const ratingVariants = cva( "group/rating inline-flex items-center data-disabled:opacity-50", { variants: { size: { sm: "gap-0.5 [--rating-size:--spacing(4)]", default: "gap-1 [--rating-size:--spacing(5)]", lg: "gap-1 [--rating-size:--spacing(7)]", }, }, defaultVariants: { size: "default", }, },);
type RatingProps = Omit< React.ComponentProps<typeof RatingPrimitive>, "className"> & VariantProps<typeof ratingVariants> & { className?: string; icon?: LucideIcon; itemClassName?: string; };
function Rating({ className, itemClassName, size, icon, max = 5, step = 0.5, children, ...props}: RatingProps) { return ( <RatingPrimitive data-size={size ?? "default"} max={max} step={step} className={cn(ratingVariants({ size }), className)} {...props} > {children ?? <RatingItem icon={icon} className={itemClassName} />} </RatingPrimitive> );}
type RatingItemProps = Omit< React.ComponentProps<typeof RatingItemPrimitive>, "className" | "children"> & { className?: string; icon?: LucideIcon;};
function RatingItem({ className, icon: Icon = StarIcon, ...props }: RatingItemProps) { return ( <RatingItemPrimitive className={cn( "text-warning relative inline-flex size-(--rating-size) shrink-0 rounded-sm transition-transform", "**:data-[slot=rating-radio]:absolute **:data-[slot=rating-radio]:inset-0 **:data-[slot=rating-radio]:cursor-pointer **:data-[slot=rating-radio]:rounded-sm **:data-[slot=rating-radio]:outline-none", "**:data-[slot=rating-radio]:focus-visible:ring-ring/50 **:data-[slot=rating-radio]:focus-visible:ring-[3px]", "group-data-disabled/rating:**:data-[slot=rating-radio]:cursor-not-allowed group-data-readonly/rating:**:data-[slot=rating-radio]:cursor-default", "data-highlighted:scale-110 group-data-readonly/rating:data-highlighted:scale-100", className, )} {...props} > <Icon aria-hidden="true" className="fill-muted text-muted-foreground/40 pointer-events-none size-full" strokeWidth={1.5} /> <span aria-hidden="true" className="pointer-events-none absolute inset-y-0 inset-s-0 w-[calc(var(--rating-fill,0)*100%)] overflow-hidden" > <Icon className="size-(--rating-size) max-w-none fill-current" strokeWidth={1.5} /> </span> </RatingItemPrimitive> );}
export { Rating, RatingItem, ratingVariants, createRatingController };export type { RatingProps, RatingItemProps };

Usage

import { Rating } from "@/components/ui/rating";
<Rating aria-label="Product rating" defaultValue={4} />

Give every rating an accessible name with aria-label or aria-labelledby. The default step is 0.5, so users can pick half stars. Pass step={1} for whole stars only.

Controlled

const [value, setValue] = React.useState<number | null>(3);

<Rating aria-label="Rating" value={value} onValueChange={setValue} />;

The value is null until someone rates. With deselectable, pressing the checked star again clears it back to null.

In a form

<form>
  <Rating aria-label="Your rating" name="rating" required />
  <button type="submit">Send review</button>
</form>

With a name, the score is submitted like any other field. required blocks submission until there is a score and shows the browser's own message.

Examples

Step

The default step is 0.5, so every star has two halves. Set step={1} for whole stars only.

Max

max sets how many stars there are.

Size

size accepts sm, default and lg.

Icon

Pass any Lucide icon to icon and color it with itemClassName.

Read Only

readOnly shows any score, including values between steps like 4.3. Name it with getValueLabel.

Deselectable

With deselectable, pressing the checked star again clears the score.

Disabled

More layouts built with Rating, such as review summaries and feedback forms, are on the Rating components page.

API Reference

Rating

The root. Renders the stars itself unless you pass RatingItem children.

PropTypeDefaultDescription
valuenumber | nullThe score. Pass it to control the rating. null means no score yet.
defaultValuenumber | nullThe score at first, when uncontrolled. A form reset returns to it.
onValueChange(value, details) => voidRuns when a user or a form reset changes the score. details.reason says why, details.cancel() stops it.
maxnumber5How many stars there are.
stepnumber0.5The smallest change, as a fraction of a star. 1 allows whole stars only.
size"sm", "default", "lg""default"Star size and gap.
iconLucideIconStarIconThe icon used for every star.
itemClassNamestringClasses for each star, for example a text color.
deselectablebooleanfalseLets a press on the checked star clear the score.
readOnlybooleanfalseShows the score as an image that can't be changed. Any value shows, like 4.3.
disabledbooleanfalseDisables every star. The score is not submitted.
requiredbooleanfalseBlocks form submission until there is a score.
namestringThe name the score submits under. Without one, nothing is submitted.
formstringThe id of a form to belong to, when the rating is outside it.
loopbooleanfalseWhether arrow keys wrap from the last star to the first.
getValueLabel(value, max) => string"3 stars"Names a score for each radio and for a read-only rating. Use it to translate.
controllerRatingControllerSets the score from anywhere. Create one with createRatingController().
render(props, state) => ReactNodeRenders your own element around the stars.
classNamestringClasses for the root.

The root has data-disabled and data-readonly attributes for styling.

RatingItem

One star. Use it as children of Rating when you need different props per star.

PropTypeDefaultDescription
indexnumberWhich star this is, from 1.
iconLucideIconStarIconThe icon for this star.
classNamestringClasses for the star.

Each star exposes --rating-fill (0 to 1) and a data-highlighted attribute while a pointer previews a score that reaches it.

createRatingController

const [controller] = React.useState(() => createRatingController());

<Rating aria-label="Rating" controller={controller} />;

controller.setValue(4);
controller.getValue();
controller.focus();

Keyboard

KeyAction
TabMoves focus into the rating, to the checked score or the first one.
ArrowRight, ArrowUpSelects the next score. With step={0.5}, this is the next half star.
ArrowLeft, ArrowDownSelects the previous score.
SpaceSelects the focused score. With deselectable, clears it when it is already checked.

Accessibility

  • Every score is a radio inside a radio group, named by getValueLabel, for example "3.5 stars".
  • A read-only rating is a single image with a label such as "Rated 4.3 out of 5" instead of a group of radios.
  • Always give the rating a name with aria-label or aria-labelledby. Use getValueLabel to translate score names.
  • Disabled ratings are skipped by Tab and are not submitted with the form.

For AI Agents

When to use

  • Collecting a score from a user: product reviews, feedback forms, post-purchase surveys.
  • Showing an average score next to a review count, with readOnly.
  • Any input where the answer is "how many out of N".

When not to use

  • Picking one of a few named options, such as Good, Okay or Bad. Use a Radio Group instead.
  • Picking a number on a wide scale, such as 0 to 100. Use a Slider.
  • Full review cards with avatar, text and date. Use the review blocks in Testimonials.

Agent notes

  • Import from @/components/ui/rating. The exports are Rating, RatingItem, ratingVariants and createRatingController.
  • onValueChange receives number | null, never a string. Type controlled state as number | null.
  • The default step is 0.5. Set step={1} when the backend only stores whole numbers.
  • Star color comes from the text-warning theme token. Override it with itemClassName, not with a hard-coded color.
  • Do not wrap stars in buttons or add click handlers. The component already renders accessible radios.

Resources