# 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.

`rating-demo.tsx`:

```tsx
import { Rating } from "@/components/ui/rating";

export default function RatingDemo() {
  return <Rating aria-label="Rating" defaultValue={3.5} />;
}
```

## Installation

```bash
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](https://shadcnuikit.com/docs/shadcn-cli). Rating is free and installs without an API key.

### Manual installation

Install the dependencies:

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

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

`components/ui/rating.tsx`:

```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

```tsx
import { Rating } from "@/components/ui/rating";
```

```tsx
<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

```tsx
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

```tsx
<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.

`rating-step.tsx`:

```tsx
import { Rating } from "@/components/ui/rating";

export default function RatingStep() {
  return (
    <div className="flex flex-col items-center gap-4">
      <Rating aria-label="Half star rating" defaultValue={2.5} />
      <Rating aria-label="Whole star rating" step={1} defaultValue={3} />
    </div>
  );
}
```

### Max

`max` sets how many stars there are.

`rating-max.tsx`:

```tsx
import { Rating } from "@/components/ui/rating";

export default function RatingMax() {
  return <Rating aria-label="Rating out of 10" max={10} step={1} defaultValue={7} />;
}
```

### Size

`size` accepts `sm`, `default` and `lg`.

`rating-size.tsx`:

```tsx
import { Rating } from "@/components/ui/rating";

export default function RatingSize() {
  return (
    <div className="flex flex-col items-center gap-4">
      <Rating aria-label="Small rating" size="sm" defaultValue={3.5} />
      <Rating aria-label="Default rating" defaultValue={3.5} />
      <Rating aria-label="Large rating" size="lg" defaultValue={3.5} />
    </div>
  );
}
```

### Icon

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

`rating-icon.tsx`:

```tsx
"use client";

import { HeartIcon } from "lucide-react";
import { Rating } from "@/components/ui/rating";

export default function RatingIcon() {
  return (
    <Rating
      aria-label="Heart rating"
      icon={HeartIcon}
      itemClassName="text-destructive"
      defaultValue={3.5}
    />
  );
}
```

### Read Only

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

`rating-read-only.tsx`:

```tsx
"use client";

import { Rating } from "@/components/ui/rating";

export default function RatingReadOnly() {
  return <Rating value={4.3} readOnly getValueLabel={(value, max) => `Rated ${value} out of ${max}`} />;
}
```

### Deselectable

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

`rating-deselectable.tsx`:

```tsx
import { Rating } from "@/components/ui/rating";

export default function RatingDeselectable() {
  return <Rating aria-label="Rating" step={1} defaultValue={3} deselectable />;
}
```

### Disabled

`rating-disabled.tsx`:

```tsx
import { Rating } from "@/components/ui/rating";

export default function RatingDisabled() {
  return <Rating aria-label="Rating" defaultValue={3.5} disabled />;
}
```

More layouts built with Rating, such as review summaries and feedback forms, are on the [Rating components](https://shadcnuikit.com/components/rating) page.

## API Reference

### Rating

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

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `number \| null` | | The score. Pass it to control the rating. `null` means no score yet. |
| `defaultValue` | `number \| null` | | The score at first, when uncontrolled. A form reset returns to it. |
| `onValueChange` | `(value, details) => void` | | Runs when a user or a form reset changes the score. `details.reason` says why, `details.cancel()` stops it. |
| `max` | `number` | `5` | How many stars there are. |
| `step` | `number` | `0.5` | The smallest change, as a fraction of a star. `1` allows whole stars only. |
| `size` | `"sm"`, `"default"`, `"lg"` | `"default"` | Star size and gap. |
| `icon` | `LucideIcon` | `StarIcon` | The icon used for every star. |
| `itemClassName` | `string` | | Classes for each star, for example a text color. |
| `deselectable` | `boolean` | `false` | Lets a press on the checked star clear the score. |
| `readOnly` | `boolean` | `false` | Shows the score as an image that can't be changed. Any value shows, like 4.3. |
| `disabled` | `boolean` | `false` | Disables every star. The score is not submitted. |
| `required` | `boolean` | `false` | Blocks form submission until there is a score. |
| `name` | `string` | | The name the score submits under. Without one, nothing is submitted. |
| `form` | `string` | | The id of a form to belong to, when the rating is outside it. |
| `loop` | `boolean` | `false` | Whether 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. |
| `controller` | `RatingController` | | Sets the score from anywhere. Create one with `createRatingController()`. |
| `render` | `(props, state) => ReactNode` | | Renders your own element around the stars. |
| `className` | `string` | | Classes 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.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `index` | `number` | | Which star this is, from 1. |
| `icon` | `LucideIcon` | `StarIcon` | The icon for this star. |
| `className` | `string` | | Classes 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

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

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

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

## Keyboard

| Key | Action |
| --- | --- |
| `Tab` | Moves focus into the rating, to the checked score or the first one. |
| `ArrowRight`, `ArrowUp` | Selects the next score. With `step={0.5}`, this is the next half star. |
| `ArrowLeft`, `ArrowDown` | Selects the previous score. |
| `Space` | Selects 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](https://shadcnuikit.com/components/radio-group) instead.
- Picking a number on a wide scale, such as 0 to 100. Use a [Slider](https://shadcnuikit.com/components/slider).
- Full review cards with avatar, text and date. Use the review blocks in [Testimonials](https://shadcnuikit.com/blocks/marketing/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**

- Markdown: [/docs/components/rating.md](https://shadcnuikit.com/docs/components/rating.md)
- Variants: [Rating components](https://shadcnuikit.com/components/rating), 6 free examples
- Install: `npx shadcn@latest add @shadcnuikit/rating1`
- MCP: call `get_item_code` with `rating1` from the [MCP Server](https://shadcnuikit.com/docs/mcp-server)
- Full index for agents: [llms.txt](https://shadcnuikit.com/llms.txt)

Source: https://shadcnuikit.com/docs/components/rating
More from Shadcn UI Kit: [llms.txt](https://shadcnuikit.com/llms.txt)