# Animated Rating for UI SDK (/docs/components/rating)

Stars fill one after another from the left, and the chosen star pops.

```tsx title="example.tsx"
import * as React from "react"

import { Rating } from "@/components/keyframery/rating"

const words = ["Poor", "Below par", "Good", "Great", "Outstanding"]

export default function RatingDemo() {
  const [score, setScore] = React.useState<number | null>(null)

  return (
    <div className="w-[360px]">
      <div className="flex items-center gap-3">
        <img src="/demo/coast-4.jpg" alt="" className="size-11 shrink-0 rounded-[10px] bg-muted object-cover" />
        <div className="min-w-0">
          <h3 className="text-[15px] font-semibold tracking-tight">Seaview flat, Whitstable</h3>
          <p className="mt-1 text-[12px] text-muted-foreground">3 nights · 8 to 11 November</p>
        </div>
      </div>

      <div className="mt-6 h-px bg-border" />

      <p id="stay" className="mt-5 text-[13px] font-medium">How was your stay?</p>
      <div className="mt-2.5 flex items-center gap-3">
        <Rating aria-labelledby="stay" value={score} onValueChange={setScore} />
        <span className="text-[13px] text-muted-foreground tabular-nums">
          {score ? words[score - 1] : "Tap a star"}
        </span>
      </div>

      <div className="mt-6 flex items-center gap-2 rounded-[10px] bg-muted/70 px-3 py-2.5">
        <Rating
          value={4.6}
          readOnly
          getValueLabel={(value, max) => `Rated ${value} out of ${max}`}
          className="gap-0 [&_[data-slot=rating-item]]:size-4 [&_[data-slot=rating-item]>span]:size-3.5"
        />
        <span className="text-[13px] font-semibold tabular-nums">4.6</span>
        <span className="text-[12px] text-muted-foreground tabular-nums">from 214 guests</span>
      </div>
    </div>
  )
}
```

## Installation [#installation]

```bash
npx shadcn@latest add @keyframery/rating
```

This adds `components/keyframery/rating.tsx` and its primitive, `components/keyframery/primitives/rating.tsx`, to your project, and installs `@ui-sdk/react`. The motion tokens are added to your global CSS the first time you install a component.

## Usage [#usage]

```tsx
import { Rating, RatingItem } from "@/components/keyframery/rating"
```

The parts and props are the same as UI SDK's Rating. For every prop, see the [UI SDK rating reference](https://ui-sdk.dev/docs/components/rating).

## What moves [#what-moves]

| Move        | What you see                                |
| ----------- | ------------------------------------------- |
| **Cascade** | Stars fill one after another from the left. |
| **Pop**     | The chosen star pops.                       |

Timing and springiness follow the [motion style](/docs/motion-styles) you set, so this component moves like the rest of your app.

## Swap the import [#swap-the-import]

Already using UI SDK's rating with your own styles? Keep your markup and change one line. The primitive adds motion and nothing else.

```tsx
// Before
import { … } from "@ui-sdk/react/rating"

// After: same parts, same props, now animated
import { … } from "@/components/keyframery/primitives/rating"
```

## Parts [#parts]

The finished component exports 2 parts:

`Rating`, `RatingItem`

## Accessibility [#accessibility]

Keyboard, focus and screen-reader behaviour come from UI SDK and are not changed. With reduced motion turned on, nothing in the rating moves: changes happen at once or with a short fade. More in [Accessibility](/docs/accessibility).

## Source [#source]

The code that lands in your project. It is yours to change.

**components/keyframery/rating.tsx**

```tsx
"use client"

/* Styled rating: the animated primitive plus the Keyframery look. */

import * as React from "react"

import { Rating as RatingRoot, RatingItem as RatingItemPart } from "@/components/keyframery/primitives/rating"
import { cn } from "@/lib/utils"

function Rating({
  className,
  children,
  ...props
}: React.ComponentProps<typeof RatingRoot>) {
  return (
    <RatingRoot
      className={cn(
        "inline-flex items-center gap-0.5 outline-none",
        "data-disabled:opacity-50",
        className as string,
      )}
      {...props}
    >
      {children ?? <RatingItem />}
    </RatingRoot>
  )
}

const starPath =
  "M8 1.9l1.83 3.72 4.1.6-2.97 2.89.7 4.08L8 11.26l-3.66 1.93.7-4.08L2.07 6.22l4.1-.6L8 1.9z"

function Star({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 16 16" aria-hidden className={cn("absolute inset-0 size-full", className)}>
      <path d={starPath} fill="currentColor" stroke="currentColor" strokeWidth="1.25" strokeLinejoin="round" />
    </svg>
  )
}

/* Each star is an empty star with a filled copy on top, clipped to --rating-fill (which the
   primitive animates, star by star from the left).
   The fill wipes in from the left; stars a pointer preview adds
   beyond the current score fill in a lighter tone. */
function RatingItem({
  className,
  children,
  ...props
}: React.ComponentProps<typeof RatingItemPart>) {
  return (
    <RatingItemPart
      className={cn(
        "group/star relative grid size-6 shrink-0 place-items-center rounded-[6px] outline-none",
        "cursor-pointer data-disabled:cursor-not-allowed data-readonly:cursor-default",
        "has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-ring has-[:focus-visible]:ring-offset-1 has-[:focus-visible]:ring-offset-background",
        className as string,
      )}
      {...props}
    >
      {children ?? (
        <span aria-hidden className="pointer-events-none relative block size-5">
          <Star className="text-muted-foreground/25 dark:text-muted-foreground/30" />
          <Star
            className={cn(
              "text-foreground [clip-path:inset(0_calc((1-var(--rating-fill,0))*100%)_0_0)]",
              /* Lighter only for stars the preview adds beyond the current score. */
              "[[data-checked]~[data-highlighted]_&]:text-foreground/50",
              "[[data-slot=rating]:not(:has([data-checked]))_[data-highlighted]_&]:text-foreground/50",
              "transition-colors duration-[calc(150ms*var(--kf-speed,1))] motion-reduce:transition-none!",
            )}
          />
        </span>
      )}
    </RatingItemPart>
  )
}

export { Rating, RatingItem }
```

**components/keyframery/primitives/rating.tsx**

```tsx
"use client"

/* Animated drop-in for `@ui-sdk/react/rating`: same parts, same props. Swap the import and keep your code.
   This file adds motion only. Colours, radii, shadows and spacing stay yours. */

import { Rating as RatingRoot, RatingItem as RatingItemPart } from "@ui-sdk/react/rating"
import * as React from "react"

import { cn } from "@/lib/utils"

export * from "@ui-sdk/react/rating"

/* UI SDK accepts a class name or a function of state; keep both working. */
function withClass<S>(base: string, className: string | ((state: S) => string | undefined) | undefined) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

/* Registering --rating-fill makes it animatable, so anything you paint from it (a clip, a
   gradient, a mask) fills smoothly with no extra work. */
const css =
  `@property --rating-fill{syntax:"<number>";inherits:true;initial-value:0}` +
  `@keyframes kf-rating-pop{0%{scale:.55}100%{scale:1}}`

function Rating(props: React.ComponentProps<typeof RatingRoot>) {
  return (
    <>
      <style href="kf-rating" precedence="default">
        {css}
      </style>
      <RatingRoot {...props} />
    </>
  )
}

/* Cascade: stars fill one after another from the left, 45ms apart; emptying is immediate.
   The star a score lands on pops in from 0.55 with an overshoot. */
function RatingItem({ className, ...props }: React.ComponentProps<typeof RatingItemPart>) {
  return (
    <RatingItemPart
      className={withClass(
        cn(
          "[transition:--rating-fill_calc(300ms*var(--kf-speed,1))_var(--ease-house)]",
          "data-filled:[transition-delay:calc((min(sibling-index(),10)-1)*calc(45ms*var(--kf-speed,1)))]",
          "data-partial:[transition-delay:calc((min(sibling-index(),10)-1)*calc(45ms*var(--kf-speed,1)))]",
          "not-data-readonly:data-checked:animate-[kf-rating-pop_calc(520ms*var(--kf-speed,1))_var(--ease-pop)_both]",
          "motion-reduce:[transition:none]! motion-reduce:animate-none!",
        ),
        className,
      )}
      {...props}
    />
  )
}

export { Rating, RatingItem }
```

## Questions

### How does the animated Rating for UI SDK move?

Cascade: Stars fill one after another from the left. Pop: The chosen star pops.

### Do I need Motion or Framer Motion for the animated Rating?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### Can I keep my own styling and only take the motion?

Yes. Import from `@/components/keyframery/primitives/rating` instead. It has the same parts and props as `@ui-sdk/react/rating` and adds motion only.

### What happens to the Rating when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
