Rating
SaveStars or a custom icon with half steps, a light hover preview, and a solid fill that sweeps across the icons when a value is picked, plus a read-only mode with a review count.
- Category
- Forms
- Version
- 0.1.0
- Frameworks
- Next.js, Vite + React
- Styling
- Tailwind CSS v4
Preview
Rating preview
How useful was this answer?
Not rated
Postgres connector
- 5 stars
- 912
- 4 stars
- 241
- 3 stars
- 78
- 2 stars
- 29
- 1 star
- 24
Installation
npx @shakenui/cli add ratingReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add rating --dry-runUsage
rating-example.tsx
"use client";
import { useState } from "react";
import { Rating } from "@/components/shaken/ui/rating";
const breakdown = [
{ stars: 5, count: 912 },
{ stars: 4, count: 241 },
{ stars: 3, count: 78 },
{ stars: 2, count: 29 },
{ stars: 1, count: 24 },
];
const total = breakdown.reduce((sum, row) => sum + row.count, 0);
export default function RatingExample() {
const [score, setScore] = useState(0);
return (
<div className="grid w-full max-w-sm gap-6">
<div className="grid gap-2">
<span id="answer-rating" className="text-sm font-medium text-zinc-950 dark:text-white">
How useful was this answer?
</span>
<Rating aria-labelledby="answer-rating" value={score} onValueChange={setScore} labels={["Not useful", "Slightly", "Somewhat", "Very", "Exactly right"]} />
</div>
<section aria-label="Reviews" className="grid gap-3 border-t border-zinc-950/[0.07] pt-5 dark:border-white/[0.08]">
<div className="flex items-center justify-between gap-3">
<h3 className="text-sm font-semibold text-zinc-950 dark:text-white">Postgres connector</h3>
<Rating readOnly value={4.6} count={total} size="sm" />
</div>
<dl className="grid gap-1.5">
{breakdown.map((row) => (
<div key={row.stars} className="grid grid-cols-[3.5rem_1fr_2.5rem] items-center gap-3 text-xs">
<dt className="text-zinc-600 dark:text-zinc-400">{row.stars} {row.stars === 1 ? "star" : "stars"}</dt>
<dd className="h-1 overflow-hidden rounded-full bg-zinc-950/[0.06] dark:bg-white/[0.09]">
<span className="block h-full rounded-full bg-zinc-950 dark:bg-white" style={{ width: `${(row.count / total) * 100}%` }} />
</dd>
<dd className="text-right font-mono text-zinc-500 tabular-nums">{row.count}</dd>
</div>
))}
</dl>
</section>
</div>
);
}States
Every state, rendered from local fixture data.
Rating states
Empty
Half steps
3.5
Read-only with count
Small, read-only
Large
Custom icon, ten steps
7
Disabled
API
| Prop | Type | Default | Description |
|---|---|---|---|
| value / defaultValue / onValueChange | number | 0 | The rating from 0 (none) to max. Read-only values may be any fraction, such as 4.6. |
| max | number | 5 | Number of icons. |
| allowHalf | boolean | false | Lets picks land on halves. |
| readOnly | boolean | false | Displays the value as one labeled image, with the number and count beside it. |
| clearable | boolean | true | Picking the current value again, Backspace, Delete, 0, or the clear button resets to 0. |
| icon | ReactNode | — | A 24 x 24 SVG with fill="currentColor" used instead of the star. |
| size | "sm" | "md" | "lg" | "md" | Icon size: 14, 20 or 28px. |
| labels | string[] | — | One word per whole step, shown beside the icons while hovering and after picking, and read out in the value text. |
| showValue | boolean | true when read-only or with labels | Shows the number or label beside the icons. |
| count | number | — | Review count shown as "(1,284)" and included in the read-only label. |
| disabled / name / locale / aria-label / aria-labelledby / id / className | boolean / string | — | State, a hidden input for forms, number formatting, naming, and attributes. |
Accessibility
- An interactive rating is one role="slider" with aria-valuemin 0, aria-valuemax max, aria-valuenow, and a value text such as "4 out of 5, Very" or "No rating".
- Right and Up step up, Left and Down step down (by a half with allowHalf), Home and End jump to the lowest and highest, Page Up and Page Down move a whole step, digits 1 to 9 set a value, and Backspace, Delete or 0 clear it when clearable.
- The clear button is labeled "Clear rating" and leaves the tab order while there is nothing to clear.
- Read-only ratings are role="img" with a label such as "Rated 4.6 out of 5, 1,284 reviews"; the visible number is hidden from screen readers to avoid reading it twice.
- The hover preview is a lighter fill and the label turns secondary, so a preview never looks like a saved value.
- The fill sweep (240 to 465ms, quint ease-out) plays only with motion allowed; with reduced motion the fill changes at once, and keyboard changes always fill in under 100ms.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/ui/rating.tsxrating- npm packages: noneReact and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/rating/0.1.0.json.
ui/rating.tsxShowHide
ui/rating.tsx
"use client";
import { type KeyboardEvent, type PointerEvent, type ReactNode, useEffect, useRef, useState } from "react";
function cx(...classes: (string | false | null | undefined)[]) {
return classes.filter(Boolean).join(" ");
}
const sizes = {
sm: { icon: 14, gap: 2, text: "text-xs" },
md: { icon: 20, gap: 4, text: "text-sm" },
lg: { icon: 28, gap: 5, text: "text-[15px]" },
} as const;
export interface RatingProps {
/** The rating, from 0 (none) to `max`. Read-only ratings may be any fraction, such as 4.6. */
value?: number;
defaultValue?: number;
onValueChange?: (value: number) => void;
/** Number of icons. */
max?: number;
/** Lets a pick land on halves. */
allowHalf?: boolean;
/** Shows the rating without taking input, for averages and review summaries. */
readOnly?: boolean;
disabled?: boolean;
/** Picking the current value again, Backspace, or the clear button resets to 0. */
clearable?: boolean;
/** A 24 x 24 SVG drawn with `fill="currentColor"`, used instead of the star. */
icon?: ReactNode;
size?: keyof typeof sizes;
/** One word per whole step, such as ["Poor", "Fair", "Good", "Great", "Excellent"]. Shown beside the icons and read out. */
labels?: string[];
/** Shows the number (or the label) beside the icons. On by default when read-only or with labels. */
showValue?: boolean;
/** Review count, shown after the value in read-only mode, as "(1,284)". */
count?: number;
/** BCP 47 locale for the value and count. */
locale?: string;
/** Accessible name. */
"aria-label"?: string;
"aria-labelledby"?: string;
/** Submits the value under this name with a hidden input. */
name?: string;
id?: string;
className?: string;
}
type Phase = "settle" | "hover" | "key";
/**
* A star rating with half steps. Interactive ratings are a slider: arrows step, Home and End jump
* to the ends, Backspace clears. Hovering previews a pick as a light fill; picking pours the solid
* fill across the icons to meet it. Read-only ratings render as one labeled image.
*/
export function Rating({
value: valueProp,
defaultValue = 0,
onValueChange,
max = 5,
allowHalf = false,
readOnly = false,
disabled = false,
clearable = true,
icon,
size = "md",
labels,
showValue = readOnly || !!labels,
count,
locale,
name,
id,
className,
...aria
}: RatingProps) {
const [inner, setInner] = useState(defaultValue);
const value = Math.max(0, Math.min(max, valueProp ?? inner));
const [hover, setHover] = useState<number | null>(null);
const [phase, setPhase] = useState<Phase>("settle");
// The fill starts empty and sweeps in once mounted.
const [mounted, setMounted] = useState(false);
useEffect(() => {
const frame = requestAnimationFrame(() => setMounted(true));
return () => cancelAnimationFrame(frame);
}, []);
const { icon: iconSize, gap, text } = sizes[size];
const stepSize = allowHalf ? 0.5 : 1;
const width = max * iconSize + (max - 1) * gap;
const interactive = !readOnly && !disabled;
const rootRef = useRef<HTMLDivElement>(null);
function offset(amount: number) {
const whole = Math.floor(amount);
return Math.min(width, whole * (iconSize + gap) + (amount - whole) * iconSize);
}
function set(next: number) {
const clamped = Math.max(0, Math.min(max, next));
if (valueProp === undefined) setInner(clamped);
if (clamped !== value) onValueChange?.(clamped);
}
function fromPointer(event: PointerEvent<HTMLDivElement>) {
const rect = event.currentTarget.getBoundingClientRect();
const x = Math.max(0, Math.min(width - 0.01, event.clientX - rect.left));
const index = Math.floor(x / (iconSize + gap));
const within = (x - index * (iconSize + gap)) / iconSize;
const fraction = allowHalf && within <= 0.5 ? 0.5 : 1;
return Math.min(max, index + fraction);
}
function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
if (!interactive) return;
const floor = clearable ? 0 : stepSize;
const moves: Record<string, () => number> = {
ArrowRight: () => value + stepSize,
ArrowUp: () => value + stepSize,
ArrowLeft: () => value - stepSize,
ArrowDown: () => value - stepSize,
Home: () => floor,
End: () => max,
PageUp: () => value + 1,
PageDown: () => value - 1,
};
let next: number | null = null;
if (moves[event.key]) next = Math.max(floor, Math.min(max, moves[event.key]!()));
else if (clearable && (event.key === "Backspace" || event.key === "Delete" || event.key === "0")) next = 0;
else if (/^[1-9]$/.test(event.key) && Number(event.key) <= max) next = Number(event.key);
if (next === null) return;
event.preventDefault();
// Keyboard changes fill almost at once; the sweep is for pointer picks.
setPhase("key");
set(Math.round(next / stepSize) * stepSize);
}
const numberFormat = new Intl.NumberFormat(locale, { maximumFractionDigits: 1, minimumFractionDigits: readOnly ? 1 : 0 });
const countFormat = new Intl.NumberFormat(locale);
const shown = hover ?? value;
const word = labels && shown > 0 ? labels[Math.max(0, Math.ceil(shown) - 1)] : undefined;
const valueText = value === 0 ? "No rating" : `${numberFormat.format(value)} out of ${max}${labels ? `, ${labels[Math.ceil(value) - 1] ?? ""}` : ""}`;
const solid = mounted ? (hover !== null ? Math.min(value, hover) : value) : 0;
const ghost = hover ?? 0;
const duration = phase === "hover" ? 140 : phase === "key" ? 90 : Math.round(240 + Math.min(max, Math.abs(value)) * 45);
const star = icon ?? (
<svg viewBox="0 0 24 24" fill="currentColor">
<path d="M11.13 3.1a.97.97 0 0 1 1.74 0l2.2 4.46a.97.97 0 0 0 .73.53l4.92.72c.8.11 1.11 1.09.54 1.65l-3.56 3.47a.97.97 0 0 0-.28.86l.84 4.9a.97.97 0 0 1-1.41 1.02l-4.4-2.31a.97.97 0 0 0-.9 0l-4.4 2.31a.97.97 0 0 1-1.41-1.02l.84-4.9a.97.97 0 0 0-.28-.86L2.74 10.46c-.57-.56-.26-1.54.54-1.65l4.92-.72a.97.97 0 0 0 .73-.53l2.2-4.46Z" />
</svg>
);
function row(tone: string) {
return (
<span aria-hidden="true" className={cx("flex", tone)} style={{ gap }}>
{Array.from({ length: max }, (_, index) => (
<span key={index} className="block shrink-0 [&>svg]:size-full" style={{ width: iconSize, height: iconSize }}>
{star}
</span>
))}
</span>
);
}
const clip = (amount: number) => `inset(0 ${width - offset(amount)}px 0 0)`;
const icons = (
<div
ref={rootRef}
id={readOnly ? id : undefined}
role={readOnly ? "img" : "slider"}
tabIndex={interactive ? 0 : undefined}
aria-label={
readOnly
? `${aria["aria-label"] ? `${aria["aria-label"]}: ` : ""}Rated ${numberFormat.format(value)} out of ${max}${count !== undefined ? `, ${countFormat.format(count)} ${count === 1 ? "review" : "reviews"}` : ""}`
: (aria["aria-label"] ?? (aria["aria-labelledby"] ? undefined : "Rating"))
}
aria-labelledby={readOnly ? undefined : aria["aria-labelledby"]}
aria-valuemin={readOnly ? undefined : 0}
aria-valuemax={readOnly ? undefined : max}
aria-valuenow={readOnly ? undefined : value}
aria-valuetext={readOnly ? undefined : valueText}
aria-disabled={!readOnly && disabled ? true : undefined}
onKeyDown={onKeyDown}
onPointerMove={(event) => {
if (!interactive || event.pointerType === "touch") return;
const next = fromPointer(event);
if (next !== hover) {
setPhase("hover");
setHover(next);
}
}}
onPointerLeave={() => {
if (!interactive) return;
setPhase("settle");
setHover(null);
}}
onClick={(event) => {
if (!interactive) return;
const next = fromPointer(event as unknown as PointerEvent<HTMLDivElement>);
setPhase("settle");
set(clearable && next === value ? 0 : next);
}}
className={cx(
"relative shrink-0 touch-manipulation rounded-md outline-hidden",
interactive && "cursor-pointer focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-4 focus-visible:outline-sky-500",
disabled && "opacity-45",
)}
style={{ width, height: iconSize }}
>
{row("text-zinc-950/[0.09] dark:text-white/[0.13]")}
{/* The preview: a light fill out to the hovered step. */}
<span
className="absolute inset-0 transition-[clip-path] duration-100 ease-out motion-reduce:transition-none"
style={{ clipPath: clip(ghost) }}
>
{row("text-zinc-950/30 dark:text-white/35")}
</span>
{/* The value: one solid layer, so a change sweeps across the icons instead of flipping each. */}
<span
className="absolute inset-0 transition-[clip-path] ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none"
style={{ clipPath: clip(solid), transitionDuration: `${duration}ms` }}
>
{row("text-zinc-950 dark:text-white")}
</span>
</div>
);
return (
<div
id={readOnly ? undefined : id}
data-slot="rating"
data-readonly={readOnly || undefined}
className={cx("inline-flex items-center gap-2 align-middle", text, className)}
>
{icons}
{showValue ? (
<span aria-hidden={readOnly || undefined} className="inline-flex min-w-0 items-baseline gap-1 tabular-nums">
{word ? (
<span className={cx("font-medium", hover !== null ? "text-zinc-600 dark:text-zinc-400" : "text-zinc-950 dark:text-white")}>{word}</span>
) : shown > 0 || readOnly ? (
<span className={cx("font-medium", hover !== null ? "text-zinc-600 dark:text-zinc-400" : "text-zinc-950 dark:text-white")}>{numberFormat.format(shown)}</span>
) : (
<span className="text-zinc-500">Not rated</span>
)}
{count !== undefined ? <span className="text-zinc-500">({countFormat.format(count)})</span> : null}
</span>
) : null}
{clearable && interactive ? (
<button
type="button"
aria-label="Clear rating"
tabIndex={value > 0 ? 0 : -1}
onClick={() => {
setPhase("settle");
set(0);
}}
className={cx(
"-ms-1 inline-flex size-6 shrink-0 items-center justify-center rounded-md text-zinc-500",
"transition-[opacity,background-color,color,scale] duration-150 ease-out motion-safe:active:scale-[0.94] motion-reduce:transition-none",
"hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white",
"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-0 focus-visible:outline-sky-500",
value > 0 ? "opacity-100" : "pointer-events-none opacity-0",
)}
>
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className="size-3.5">
<path d="m4.5 4.5 7 7m0-7-7 7" />
</svg>
</button>
) : null}
{name ? <input type="hidden" name={name} value={value} /> : null}
</div>
);
}