Rating Group 문서
Rating Group은 별처럼 커스터마이즈 가능한 항목들로 사용자가 평가(평점)를 남길 수 있게 해 주는 컴포넌트예요. 별점 하나만으로도 접근성과 키보드 탐색, 반쪽 평가까지 갖춘 완성도 높은 평점 UI를 만들 수 있어요.
출처: 문서
본문
아래 예시는 별을 5개 렌더링하고 value에 바인딩한 기본 Rating Group이에요. RatingGroup.Root가 항목 목록을 items로 내려 주고, 그 안에서 RatingGroup.Item을 반복해 그려요.
<script lang="ts">
import { RatingGroup } from "bits-ui";
import Star from "phosphor-svelte/lib/Star";
let value = $state(3);
</script>
<RatingGroup.Root bind:value max={5} class="flex gap-1">
{#snippet children({ items })}
{#each items as item (item.index)}
<RatingGroup.Item
index={item.index}
class="text-foreground hover:text-foreground data-[state=inactive]:text-muted-foreground group size-10 cursor-pointer transition-colors md:size-8"
>
<Star class="size-full" weight="fill" />
</RatingGroup.Item>
{/each}
{/snippet}
</RatingGroup.Root>
구조 (Structure)
Rating Group의 기본 구조는 RatingGroup.Root가 항목 목록을 items로 내려 주고, 그 안에서 RatingGroup.Item을 반복해 그리는 방식이에요. 각 항목은 item.state가 "active"인지에 따라 채운 별이나 빈 별을 보여 줘요.
<script lang="ts">
import { RatingGroup } from "bits-ui";
</script>
<RatingGroup.Root max={5}>
{#snippet children({ items })}
{#each items as item (item.index)}
<RatingGroup.Item index={item.index}>
{#if item.state === "active"}
⭐
{:else}
☆
{/if}
</RatingGroup.Item>
{/each}
{/snippet}
</RatingGroup.Root>
재사용 컴포넌트 (Reusable Components)
RatingGroup 프리미티브로 애플리케이션 곳곳에서 쓸 수 있는 나만의 평점 컴포넌트를 만드는 걸 권장해요.
아래 예시는 최대 평점과 스타일을 설정할 수 있는 MyRatingGroup 컴포넌트를 만든 모습이에요.
MyRatingGroup.svelte
<script lang="ts">
import { RatingGroup, type WithoutChildrenOrChild } from "bits-ui";
import Star from "phosphor-svelte/lib/Star";
import StarHalf from "phosphor-svelte/lib/StarHalf";
let {
value = $bindable(0),
ref = $bindable(null),
showLabel = true,
max = 5,
...restProps
}: WithoutChildrenOrChild<RatingGroup.RootProps> & {
showLabel?: boolean;
} = $props();
</script>
<div class="flex flex-col gap-2">
<RatingGroup.Root bind:value bind:ref {max} {...restProps}>
{#snippet children({ items })}
{#each items as item (item.index)}
<RatingGroup.Item index={item.index}>
{#if item.state === "inactive"}
<Star />
{:else if item.state === "active"}
<Star weight="fill" />
{:else if item.state === "partial"}
<StarHalf weight="fill" />
{/if}
</RatingGroup.Item>
{/each}
{/snippet}
</RatingGroup.Root>
{#if showLabel}
<p class="text-muted-foreground text-sm">
Rating: {value} out of {max} stars
</p>
{/if}
</div>
그리고 만든 MyRatingGroup 컴포넌트는 애플리케이션에서 이렇게 사용하면 돼요.
+page.svelte
<script lang="ts">
import MyRatingGroup from "$lib/components/MyRatingGroup.svelte";
let productRating = $state(4);
</script>
<MyRatingGroup bind:value={productRating} max={5} allowHalf />
값 상태 다루기 (Managing Value State)
이번 절에서는 컴포넌트의 value 상태를 어떻게 다루는지 설명할게요.
양방향 바인딩 (Two-Way Binding)
간단하고 자동으로 상태를 동기화하고 싶다면 bind:value를 사용해요.
<script lang="ts">
import { RatingGroup } from "bits-ui";
let myRating = $state(3);
</script>
<button onclick={() => (myRating = 5)}> Give 5 stars </button>
<RatingGroup.Root bind:value={myRating} max={5}>
{#snippet children({ items })}
{#each items as item (item.index)}
<RatingGroup.Item index={item.index}>
{#if item.state === "active"}⭐{:else}☆{/if}
</RatingGroup.Item>
{/each}
{/snippet}
</RatingGroup.Root>
완전 제어 (Fully Controlled)
상태의 읽기와 쓰기를 모두 직접 제어하고 싶다면 Function Binding을 사용해요.
<script lang="ts">
import { RatingGroup } from "bits-ui";
let myRating = $state(0);
function getValue() {
return myRating;
}
function setValue(newValue: number) {
// Add custom logic here, like validation or analytics
if (newValue >= 0 && newValue <= 5) {
myRating = newValue;
}
}
</script>
<RatingGroup.Root bind:value={getValue, setValue} max={5}>
{#snippet children({ items })}
{#each items as item (item.index)}
<RatingGroup.Item index={item.index}>
{#if item.state === "active"}⭐{:else}☆{/if}
</RatingGroup.Item>
{/each}
{/snippet}
</RatingGroup.Root>
HTML 폼 (HTML Forms)
RatingGroup.Root 컴포넌트에 name prop을 설정하면, 평점 값을 폼에 제출하기 위한 숨겨진 입력 요소가 렌더링돼요.
<RatingGroup.Root name="productRating" max={5}>
<!-- ... -->
</RatingGroup.Root>
필수 (Required)
숨겨진 입력 요소를 required로 만들려면 RatingGroup.Root 컴포넌트에 required prop을 설정하면 돼요.
<RatingGroup.Root required max={5}>
<!-- ... -->
</RatingGroup.Root>
반쪽 평가 (Half Ratings)
allowHalf prop을 true로 설정하면 Rating Group은 반쪽 평가를 지원해요. 이 덕분에 3.5점처럼 더 정밀한 평점을 줄 수 있어요.
<RatingGroup.Root allowHalf>
{#snippet children({ items })}
{#each items as item (item.index)}
<RatingGroup.Item index={item.index}>
{#if item.state === "inactive"}
<Star class="size-full" />
{:else if item.state === "active"}
<Star class="size-full fill-current" weight="fill" />
{:else if item.state === "partial"}
<StarHalf class="size-full fill-current" weight="fill" />
{/if}
</RatingGroup.Item>
{/each}
{/snippet}
</RatingGroup.Root>
코드 펼치기 (Expand Code)
<script lang="ts">
import { RatingGroup } from "bits-ui";
import Star from "phosphor-svelte/lib/Star";
import StarHalf from "phosphor-svelte/lib/StarHalf";
let value = $state(3);
</script>
<RatingGroup.Root bind:value max={5} allowHalf={true} class="flex gap-1">
{#snippet children({ items })}
{#each items as item (item.index)}
<RatingGroup.Item
index={item.index}
class="text-foreground data-[state=inactive]:text-muted-foreground size-10 cursor-pointer transition-colors data-[readonly]:cursor-default md:size-8"
>
{#if item.state === "inactive"}
<Star class="size-full" />
{:else if item.state === "active"}
<Star class="size-full fill-current" weight="fill" />
{:else if item.state === "partial"}
<StarHalf class="size-full fill-current" weight="fill" />
{/if}
</RatingGroup.Item>
{/each}
{/snippet}
</RatingGroup.Root>
읽기 전용 모드 (Readonly Mode)
readonly prop을 true로 설정하면 Rating Group을 읽기 전용으로 만들 수 있어요. 사용자 상호작용 없이 기존 평점을 표시할 때 유용해요.
<RatingGroup.Root readonly value={4.5}>
<!-- ... -->
</RatingGroup.Root>
비활성화 상태 (Disabled State)
disabled prop을 true로 설정하면 Rating Group 전체를 비활성화할 수 있어요.
<RatingGroup.Root disabled max={5}>
<!-- ... -->
</RatingGroup.Root>
호버 미리보기 (Hover Preview)
기본적으로 Rating Group은 항목 위에 마우스를 올렸을 때 잠재적인 평점을 미리 보여 줘요. 이 동작을 끄려면 hoverPreview를 false로 설정하면 돼요.
<RatingGroup.Root hoverPreview={false} max={5}>
{#snippet children({ items })}
{#each items as item (item.index)}
<RatingGroup.Item index={item.index}>
{#if item.state === "active"}⭐{:else}☆{/if}
</RatingGroup.Item>
{/each}
{/snippet}
</RatingGroup.Root>
비활성화하면 현재 선택된 평점만 강조되고, 항목 위에 마우스를 올려도 선택될 평점의 미리보기는 보여 주지 않아요.
코드 펼치기 (Expand Code)
<script lang="ts">
import { RatingGroup } from "bits-ui";
import Star from "phosphor-svelte/lib/Star";
let value = $state(2);
</script>
<div class="flex select-none flex-col gap-4">
<div class="flex flex-col gap-2">
<h3 class="text-sm font-medium">Hover preview disabled</h3>
<p class="text-muted-foreground text-sm">
Only shows selected rating on hover, no preview of potential selection.
</p>
</div>
<RatingGroup.Root bind:value max={5} hoverPreview={false} class="flex gap-1">
{#snippet children({ items })}
{#each items as item (item.index)}
<RatingGroup.Item
index={item.index}
class="text-muted-foreground data-[state=active]:text-foreground group size-8 cursor-pointer transition-colors md:size-6"
>
<Star
class="size-full group-data-[state=active]:fill-current"
weight="fill"
/>
</RatingGroup.Item>
{/each}
{/snippet}
</RatingGroup.Root>
<p class="text-muted-foreground text-sm">
Rating: {value} out of 5 stars
</p>
</div>
RTL 지원 (RTL Support)
Rating Group은 오른쪽에서 왼쪽으로 읽는(RTL) 텍스트 방향에 자동으로 맞춰져요. 부모 요소에 dir="rtl" 속성을 설정하기만 하면 돼요.
<div dir="rtl">
<RatingGroup.Root max={5}>
{#snippet children({ items })}
{#each items as item (item.index)}
<RatingGroup.Item index={item.index}>
{#if item.state === "active"}⭐{:else}☆{/if}
</RatingGroup.Item>
{/each}
{/snippet}
</RatingGroup.Root>
</div>
RTL 모드에서는 화살표 키 탐색 방향이 시각적 방향에 맞게 자동으로 반전돼요.
코드 펼치기 (Expand Code)
<script lang="ts">
import { RatingGroup } from "bits-ui";
import Star from "phosphor-svelte/lib/Star";
import StarHalf from "phosphor-svelte/lib/StarHalf";
let value = $state(3);
</script>
<div class="flex flex-col gap-4" dir="rtl">
<div class="flex flex-col gap-2">
<h3 class="text-sm font-medium">تقييم بالنجوم (RTL)</h3>
<p class="text-muted-foreground text-sm">
Rating group with right-to-left text direction.
</p>
</div>
<RatingGroup.Root bind:value max={5} class="flex gap-1" allowHalf>
{#snippet children({ items })}
{#each items as item (item.index)}
<RatingGroup.Item
index={item.index}
class="text-muted-foreground data-[state=active]:text-foreground data-[state=partial]:text-foreground size-8 cursor-pointer transition-colors md:size-6"
>
{#if item.state === "partial"}
<StarHalf
class="size-full fill-current rtl:scale-x-[-1]"
weight="fill"
/>
{:else if item.state === "active"}
<Star class="size-full fill-current" weight="fill" />
{:else}
<Star class="size-full" />
{/if}
</RatingGroup.Item>
{/each}
{/snippet}
</RatingGroup.Root>
<p class="text-muted-foreground text-sm">
التقييم: {value} من 5 نجوم
</p>
</div>
최대 평점 (Maximum Rating)
max prop은 최대 평점 값과 렌더링할 항목 수를 결정해요. (기본값은 5예요.)
<RatingGroup.Root max={3}>
{#snippet children({ items })}
{#each items as item (item.index)}
<RatingGroup.Item index={item.index}>
{item.index + 1}
</RatingGroup.Item>
{/each}
{/snippet}
</RatingGroup.Root>
최소 평점 (Minimum Rating)
min prop은 요구되는 최소 평점 값을 설정해요. 설정하면 사용자가 이 값보다 낮은 평점을 선택할 수 없고, 평점을 지워도 최소값 아래로 내려가지 않아요. (기본값은 0이에요.)
<RatingGroup.Root min={3} value={3}>
{#snippet children({ items })}
{#each items as item (item.index)}
<RatingGroup.Item index={item.index}>
{#if item.state === "active"}⭐{:else}☆{/if}
</RatingGroup.Item>
{/each}
{/snippet}
</RatingGroup.Root>
이건 최소 1점 평점이 필수인 피드백 폼처럼 일정 수준 이상의 평점을 요구하는 상황에서 유용해요.
접근성 (Accessibility)
RatingGroup 컴포넌트는 평점 인터페이스를 위한 WAI-ARIA 모범 사례를 따르는 폭넓은 접근성 기능을 구현하고 있어요.
ARIA 구현 (ARIA Implementation)
이 컴포넌트는 radiogroup 패턴 대신 슬라이더 패턴을 사용해요. 평점 인터페이스에서 스크린 리더 지원이 더 좋아지죠.
- 루트 요소: 완전한 ARIA 슬라이더 속성을 가진
role="slider" - 평점 항목: 중복된 안내를 피하기 위한
role="presentation" - 값 전달: 현재 상태를 나타내는
aria-valuenow,aria-valuemin,aria-valuemax - 커스텀 설명: 문맥에 맞는 평점 설명을 위한
aria-valuetext - 상태 표시:
aria-disabled,aria-required,aria-orientation
사용자가 화살표 키로 탐색하면 스크린 리더가 즉시 새 평점 값을 알려 줘서 실시간 피드백을 제공해요.
키보드 탐색 전략 (Keyboard Navigation Strategy)
키보드 구현은 플랫폼 관례를 따르면서 평점 특화 기능을 더했어요.
숫자 직접 입력 (Direct Number Input)
평점을 정하는 가장 효율적인 방법이에요. 사용자가 원하는 정확한 평점을 입력할 수 있어요.
- 정수 평점:
3을 입력하면 별 3개로 설정돼요 - 반쪽 평점:
2.5를 입력하면 2.5점으로 설정돼요 (allowHalf가 켜져 있을 때) - 평점 지우기:
0을 입력하면 평점이 제거돼요 (최소값 제약은 존중돼요) - 입력 검증: 잘못된 숫자는 무시되고, 값은 min/max 범위 안으로 조정돼요
화살표 키 탐색 (Arrow Key Navigation)
탐색은 평점 정밀도와 텍스트 방향 모두에 맞춰져요.
- 기본 모드: 화살표 키로 1씩 증가/감소해요
- 반쪽 평점 모드: 더 세밀한 조절을 위해 화살표 키로 0.5씩 증가/감소해요
- RTL 지원: 오른쪽에서 왼쪽 레이아웃에서는 좌우 화살표가 자동으로 반전돼요
- 범위 존중: min/max 값에서 탐색이 멈춰요
빠른 탐색 (Quick Navigation)
Home: 최소 평점으로 이동해요 (최소값이 없으면 1로)End: 최대 평점으로 이동해요PageUp/PageDown: 1씩 증가/감소해요 (화살표 키의 대안)
포커스 관리 (Focus Management)
컴포넌트는 포커스를 지능적으로 다뤄요.
- 마우스 상호작용: 평점 항목을 클릭하면 루트 슬라이더가 자동으로 포커스돼요
- 키보드 포커스: 탭 정지점 하나 — Rating Group 전체가 하나의 포커스 가능한 단위로 동작해요
- 시각적 피드백: 루트 컨테이너에 포커스 스타일이 적용돼요
- 비활성화 상태: 비활성화되면 컴포넌트는 포커스가 불가능해져요
접근성 커스터마이즈 (Customizing Accessibility)
커스텀 aria-valuetext로 접근성 경험을 더 풍성하게 만들 수 있어요.
<RatingGroup.Root
"aria-valuetext"={(value, max) => {
if (value === 0) return "No rating selected";
return `${value} out of ${max} stars. ${value >= 4 ? "Excellent" : value >= 3 ? "Good" : "Fair"} rating.`;
}}
>
<!-- ... -->
</RatingGroup.Root>
API Reference
RatingGroup.Root
The rating group component used to group rating items under a common name for form submission.
| Property | Type | Description | Details |
|---|---|---|---|
value $bindable |
number |
The value of the rating group. You can bind to this value to control the rating group's value from outside the component.Default: 0 |
|
onValueChange |
function - (value: number) => void |
A callback that is fired when the rating group's value changes.Default: —— undefined |
|
disabled |
boolean |
Whether or not the radio group is disabled. This prevents the user from interacting with it.Default: false |
|
required |
boolean |
Whether or not the radio group is required.Default: false |
|
name |
string |
The name of the rating group used in form submission. If provided, a hidden input element will be rendered to submit the value of the rating group.Default: —— undefined |
|
min |
number |
The minimum value of the rating group.Default: 0 |
|
max |
number |
The maximum value of the rating group.Default: 5 |
|
allowHalf |
boolean |
Whether or not the rating group allows half values.Default: false |
|
readonly |
boolean |
Whether or not the rating group is readonly.Default: false |
|
orientation |
enum - 'vertical' | 'horizontal' |
The orientation of the rating group. This will determine how keyboard navigation will work within the component.Default: 'horizontal' |
|
hoverPreview |
boolean |
Whether or not the rating group shows a preview of the rating when hovering over the items.Default: false |
|
aria-valuetext |
union - string | (value: number, max: number) => string |
The text that describes the rating group's value.Default: `${value} out of ${max}` |
|
ref $bindable |
HTMLDivElement |
The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null |
|
children |
Snippet - type RatingGroupItemState = "active" | "partial" | "inactive" type RatingGroupItemData = { index: number state: RatingGroupItemState } type ChildrenSnippetProps = { items: RatingGroupItemData[] value: number max: number } |
The children content to render.Default: —— undefined |
|
child |
Snippet - type RatingGroupItemState = "active" | "partial" | "inactive" type RatingGroupItemData = { index: number state: RatingGroupItemState } type ChildSnippetProps = { items: RatingGroupItemData[] value: number max: number props: Record<string, unknown> } |
Use render delegation to render your own element. See Child Snippet docs for more information.Default: —— undefined |
| Data Attribute | Value | Description | Details |
|---|---|---|---|
data-orientation |
enum - 'vertical' | 'horizontal' |
The orientation of the rating group. | |
data-disabled |
'' |
Present when the rating group is disabled. | |
data-readonly |
'' |
Present when the rating group is readonly. | |
data-rating-group-root |
'' |
Present on the root element. |
RatingGroup.Item
An rating item, which must be a child of the RatingGroup.Root component.
| Property | Type | Description | Details |
|---|---|---|---|
index required |
number |
The index of the rating item.Default: —— undefined |
|
disabled |
boolean |
Whether the rating item is disabled.Default: false |
|
ref $bindable |
HTMLDivElement |
The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null |
|
children |
Snippet - type RatingGroupItemState = "active" | "partial" | "inactive" type ChildrenSnippetProps = { state: RatingGroupItemState } |
The children content to render.Default: —— undefined |
|
child |
Snippet - type RatingGroupItemState = "active" | "partial" | "inactive" type ChildSnippetProps = { state: RatingGroupItemState props: Record<string, unknown> } |
Use render delegation to render your own element. See Child Snippet docs for more information.Default: —— undefined |
| Data Attribute | Value | Description | Details |
|---|---|---|---|
data-disabled |
'' |
Present when the rating group is disabled. | |
data-readonly |
'' |
Present when the rating group is readonly. | |
data-value |
'' |
The value of the rating item. | |
data-state |
enum - 'checked' | 'unchecked' |
The rating item's checked state. | |
data-orientation |
enum - 'vertical' | 'horizontal' |
The orientation of the parent rating group. | |
data-rating-group-item |
'' |
Present on the rating item element. |
더 알아보기 (Learn more)
Rating Group은 allowHalf, min, max로 평점의 범위와 정밀도를 조절하고, 키보드·ARIA 지원까지 기본으로 갖춰 있어요. 여러 항목 중 하나만 고르는 Radio Group이나 목록에서 값을 선택하는 Select와 함께 보면, 선택형 입력 컴포넌트들을 목적에 맞게 구분해 쓸 수 있어요.