Skip to content
Esc
↑↓navigate↵open⌘Jpreview
On this page

Rating for Astro

Astro star displays for a score, with an optional control to set it.

Default

Interactive

Installation

bunx --bun shadcn@latest add @gnostic/rating
npx shadcn@latest add @gnostic/rating
pnpm dlx shadcn@latest add @gnostic/rating

Complete the Installation guide first. Then copy the component files below.

No extra packages are required.

Copy the files

src/components/ui/rating/index.ts
export { default as Rating } from './rating.astro'
export { default as RatingValue } from './rating-value.astro'

export type { RatingProps } from './types.ts'
src/components/ui/rating/rating.astro
---
import type { HTMLAttributes, HTMLTag, Polymorphic } from "astro/types"
import Star from "@lucide/astro/icons/star"

import { cn } from "cn"
import type { RatingProps } from "./types.ts"
import { mergeStyles } from "../../../lib/merge-styles.ts"

/**
 * Star score.
 * Div attributes pass through. `value` and `interactive` come from `RatingProps`.
 */
type Props<T extends HTMLTag = "div"> = Polymorphic<{ as: T }> &
  Omit<HTMLAttributes<T>, "name"> &
  RatingProps

const {
  as: Tag = "div",
  class: className,
  interactive = false,
  max = 5,
  value,
  name,
  label = "Rating",
  disabled = false,
  starColor = "var(--primary)",
  style: styleProp,
  ...props
} = Astro.props

/** Use a whole star count of at least 1. */
const starCount = Number.isFinite(max) ? Math.max(1, Math.trunc(max)) : 5

/** Keep a non-numeric score at 0, and keep every score inside the star count. */
const numericValue = Number(value)
const score = Number.isFinite(numericValue)
  ? Math.min(starCount, Math.max(0, numericValue))
  : 0

/** Screen-reader text for the current score. */
const valueText = `${score} out of ${starCount}`

const style = mergeStyles(
  {
    "--rating-value": String(score),
    "--star-color": starColor,
  },
  styleProp,
)
---

<Tag
  data-slot="rating"
  data-interactive={interactive ? "" : undefined}
  data-disabled={interactive && disabled ? "" : undefined}
  data-max={starCount}
  role={interactive ? undefined : "img"}
  aria-label={interactive ? undefined : valueText}
  class={cn(
    "relative flex w-fit items-center text-base gap-4",
    interactive && !disabled && "cursor-pointer select-none",
    interactive &&
      !disabled &&
      "rounded-sm outline-none has-focus-visible:ring-2 has-focus-visible:ring-ring",
    interactive && disabled && "cursor-not-allowed opacity-64",
    className,
  )}
  style={style}
  {...props}
>
  <div
    class={"flex items-center gap-1 text-[size:inherit]"}
    data-slot="rating-stars"
  >
    {Array.from({ length: starCount }, (_, index) => (
      <span
        data-slot="rating-star"
        data-value={index + 1}
        aria-hidden="true"
        class="text-muted-foreground/25 relative inline-flex size-[1em] shrink-0"
        style={{ "--star-index": String(index + 1) }}
      >
        <Star class="size-[1em] fill-current" />
        <span
          data-slot="rating-star-fill"
          class="text-(--star-color) pointer-events-none absolute inset-y-0 inset-s-0 overflow-hidden transition-[width] duration-150"
          style={{
            // Fill one star from the shared score.
            // `--star-index` starts at 1. A score of 3.5 fills the first three stars
            // and half of the fourth.
            width:
              "calc(clamp(0, var(--rating-value) - (var(--star-index) - 1), 1) * 100%)",
          }}
        >
          <Star class="size-[1em] fill-current" />
        </span>
      </span>
    ))}
  </div>
  {interactive && (
    <input
      data-slot="rating-input"
      type="range"
      min={0}
      max={starCount}
      step={1}
      value={score}
      name={name}
      disabled={disabled}
      aria-label={label}
      aria-valuetext={valueText}
      class="pointer-events-none sr-only outline-none"
    />
  )}
  <slot />
</Tag>

<script>
  /** Roots already bound on this page. A later page load skips them. */
  const bound = new WeakSet<HTMLElement>()

  /**
   * Clicks and keyboard input on one rating.
   * The range control stores the score. The stars read `--rating-value`.
   */
  function bindRating(root: HTMLElement) {
    if (bound.has(root)) return
    const input = root.querySelector<HTMLInputElement>(
      "[data-slot='rating-input']",
    )
    if (!input) return
    bound.add(root)

    const max = Number(root.dataset.max ?? input.max)

    /**
     * Paint the stars for a score.
     * `announce` copies the saved score into this rating's value text.
     * A hover preview does not. The value text must be inside this rating.
     */
    const paint = (raw: number, announce = false) => {
      const next = Number.isFinite(raw) ? Math.min(max, Math.max(0, raw)) : 0
      root.style.setProperty("--rating-value", String(next))
      if (!announce) return
      const text = String(next)
      input.setAttribute("aria-valuetext", `${text} out of ${max}`)
      for (const valueElement of root.querySelectorAll<HTMLElement>(
        "[data-slot='rating-value']",
      )) {
        if (valueElement.closest("[data-slot='rating']") !== root) continue
        valueElement.textContent = text
      }
    }

    /** Star value under the pointer, when the event hit a star in this root. */
    const starFrom = (target: EventTarget | null) => {
      if (!(target instanceof Element)) return
      const star = target.closest("[data-slot='rating-star']")
      if (!(star instanceof HTMLElement) || !root.contains(star)) return
      return star.dataset.value
    }

    input.addEventListener("input", () => paint(input.valueAsNumber, true))
    input.addEventListener("focus", () => paint(input.valueAsNumber, true))

    // hover preview - no announcement, only visual preview
    root.addEventListener("pointermove", (event) => {
      if (input.disabled) return
      const next = Number(starFrom(event.target) ?? input.valueAsNumber)

      paint(next)
    })
    root.addEventListener("pointerleave", () => paint(input.valueAsNumber))

    // click commits the value to the input
    root.addEventListener("click", (event) => {
      if (input.disabled) return
      const next = starFrom(event.target)
      if (!next) return
      input.value = next
      input.dispatchEvent(new Event("input", { bubbles: true }))
      input.dispatchEvent(new Event("change", { bubbles: true }))
      input.focus({ preventScroll: true })
    })

    // The value returns to the initial score after the reset event.
    input.form?.addEventListener("reset", () => {
      requestAnimationFrame(() => paint(input.valueAsNumber, true))
    })

    // Read the range control once. Later changes reuse the input listener.
    paint(input.valueAsNumber, true)
  }

  const initialize = () => {
    for (const root of document.querySelectorAll<HTMLElement>(
      "[data-slot='rating'][data-interactive]",
    ))
      bindRating(root)
  }

  initialize()
  document.addEventListener("astro:page-load", initialize)
</script>
src/components/ui/rating/rating-value.astro
---
import type { HTMLAttributes, HTMLTag, Polymorphic } from "astro/types"
import type { RatingValueProps } from "./types"
import { cn } from "cn"

/**
 * Score text for the parent rating.
 * Element attributes such as `class` pass through.
 * Place this part inside `Rating`. It has no score prop.
 */
type Props<T extends HTMLTag = "span"> = Polymorphic<{ as: T }> &
  HTMLAttributes<T> &
  RatingValueProps

const { as: Tag = "span", class: className, ...props } = Astro.props
---

<Tag
  data-slot="rating-value"
  class={cn("text-muted-foreground text-sm tabular-nums", className)}
  {...props}
/>
src/components/ui/rating/types.ts
import type { HTMLTag } from 'astro/types'
/**
 * Props for a star score.
 * Div attributes such as `class` and `id` pass through.
 * The root element can change with `as`. The default element is `div`.
 */
export interface RatingProps {
    /**
     * Score to show.
     * A fraction fills part of the next star.
     */
    value: number
    /**
     * Let the visitor set the score.
     * The component then renders a range control. A click on a star sets a
     * whole number of stars. Arrow keys change that control by one star.
     *
     * @default false
     */
    interactive?: boolean
    /**
     * Number of stars.
     * Values below 1 become 1.
     *
     * @default 5
     */
    max?: number
    /**
     * Form field name for the range control.
     * Used only when `interactive` is set. The submitted value is a number
     * from 0 through `max`.
     */
    name?: string
    /**
     * Accessible name for the range control.
     * Used only when `interactive` is set. Use the same words in a visible caption.
     *
     * @default "Rating"
     */
    label?: string
    /**
     * Block changes to the score.
     * Used only when `interactive` is set. A disabled control is not submitted.
     *
     * @default false
     */
    disabled?: boolean
    /**
     * Color of the stars.
     *
     * @default "var(--primary)"
     */
    starColor?: string
    /**
     * The type of the element to render.
     *
     * @default "div"
     */
    as?: HTMLTag
}

export interface RatingValueProps {
    /**
     * Score to show.
     * A fraction fills part of the next star.
     */
    value: number
    /**
     * The type of the element to render.
     *
     * @default "span"
     */
    as?: HTMLTag
}

Usage

import { Rating, RatingValue } from "@/components/ui/rating"
<Rating value={4.5} />
<Rating interactive name="rating" value={0} label="Rating">
  <RatingValue />
</Rating>

Rating defaults to 5 when no value is provided. A fraction fills part of the next star.

Examples

Interactive Rating

Set interactive to let the visitor choose a score. Pass value={0} to start with empty stars. Give the control a name when the page submits a form, and a label that matches the visible caption.

Put RatingValue inside Rating to show the saved score beside the stars. It takes no score prop.

Composition

RatingValue is optional. Place it inside the Rating it should show. The rating reads its own range control and writes that score into the value text. One rating has one set of listeners. A second rating on the page does not share them.

A value outside Rating does not update. A hover preview changes the stars only. The number changes when the score is saved.

API Reference

RatingProps

PropType
valuenumber

Score to show. A fraction fills part of the next star.

Typenumber
interactive?boolean

Let the visitor set the score. The component then renders a range control. A click on a star sets a whole number of stars. Arrow keys change that control by one star.

Typeboolean
Defaultfalse
max?number

Number of stars. Values below 1 become 1.

Typenumber
Default5
name?string

Form field name for the range control. Used only when `interactive` is set. The submitted value is a number from 0 through `max`.

Typestring
label?string

Accessible name for the range control. Used only when `interactive` is set. Use the same words in a visible caption.

Typestring
Default"Rating"
disabled?boolean

Block changes to the score. Used only when `interactive` is set. A disabled control is not submitted.

Typeboolean
Defaultfalse
starColor?string

Color of the stars.

Typestring
Default"var(--primary)"
as?HTMLTag

The type of the element to render.

TypeHTMLTag
Default"div"

Div attributes such as class and id pass through. The root element can change with as. The default element is div.

RatingValue

RatingValue has no score prop. Element attributes such as class and id pass through. The root element can change with as. The default element is span. Place it inside Rating.

Read the installed source for the component source.

When to use Rating

Use Rating to show a score. Place the score, scale, and review count in nearby text when they matter. Keep the displayed value consistent with the source data.

Set interactive when the visitor must choose a score. The range control stores the value and sends input and change events.

Keyboard and behavior

A static rating is an image with the text “4 out of 5”. It is not a control.

Set interactive to add a range control. Tab reaches that control. Arrow keys change the score by one star. A pointer click on a star sets that score. Move the pointer across the stars to preview a score. The control name comes from label. RatingValue shows the saved score, not the preview.

A click or an arrow key sets a whole number of stars. The minimum value is 0.

Theme and layout

Check filled and unfilled stars in both modes. Do not use color alone to show the difference. Filled stars use the primary color. Empty stars use a muted color.