본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

레이팅(Rating)

원문 보기 위키 갱신

아이콘 집합을 사용해 사용자가 항목을 평가(rating)할 수 있게 해주는 컴포넌트예요.

출처: 문서

본문

Import

import { Rating } from "@kobalte/core/rating";
// or
import { Root, Label, ... } from "@kobalte/core/rating";

Features

  • 절반 값 단위로 정밀한 평가가 가능해요.
  • 폼 리셋 이벤트와 동기화돼요.
  • 보조 기술을 위한 그룹 및 레이팅 라벨링을 지원해요.
  • 제어(controlled) 또는 비제어(uncontrolled) 방식으로 사용할 수 있어요.

Anatomy

레이팅은 다음 요소들로 구성돼요:

  • Rating: 레이팅의 루트 컨테이너예요.
  • Rating.Control: 레이팅 항목들의 컨테이너예요.
  • Rating.Label: 레이팅에 대한 정보를 사용자에게 주는 라벨이에요.
  • Rating.HiddenInput: 레이팅 안에 시각적으로 숨겨진 네이티브 html input이에요.
  • Rating.Description: 레이팅에 대한 더 많은 정보를 사용자에게 주는 설명이에요.
  • Rating.ErrorMessage: 레이팅의 유효성 검사 오류를 해결하는 방법을 사용자에게 알려주는 오류 메시지예요.

레이팅 항목은 다음 요소들로 구성돼요:

  • Rating.Item: 레이팅 항목의 루트 컨테이너예요.
  • Rating.ItemControl: 레이팅 항목을 시각적으로 나타내는 요소예요.
  • Rating.ItemLabel: 레이팅 항목에 대한 정보를 사용자에게 주는 라벨이에요.
  • Rating.ItemDescription: 레이팅 항목에 대한 더 많은 정보를 사용자에게 주는 설명이에요.
<Rating>
	<Rating.Label />
	<Rating.Control>
        <Rating.Item>
            <Rating.ItemControl />
            <Rating.ItemLabel />
            <Rating.ItemDescription />
        </Rating.Item>
    <Rating.Control>
	<Rating.HiddenInput />
	<Rating.Description />
	<Rating.ErrorMessage />
</Rating>

Example

Usage

Default value

defaultValue prop으로 초기 비제어(uncontrolled) 값을 제공할 수 있어요.

<Rating defaultValue={3}>
	<Rating.Control>
		<Index each={Array(5)}>
			{_ => (
				<Rating.Item>
					<Rating.ItemControl>
						<StarIcon />
					</Rating.ItemControl>
				</Rating.Item>
			)}
		</Index>
	</Rating.Control>
</Rating>

Controlled value

value prop을 사용해 값을 제어(controlled) 방식으로 만들 수 있어요. 사용자가 레이팅을 선택하면 onChange 이벤트가 발생하며 새 값을 받아요.

import { createSignal } from "solid-js";

function ControlledExample() {
	const [value, setValue] = createSignal(0);

	return (
		<>
			<Rating value={value()} onChange={setValue}>
				<Rating.Control>
					<Index each={Array(5)}>
						{_ => (
							<Rating.Item>
								<Rating.ItemControl>
									<StarIcon />
								</Rating.ItemControl>
							</Rating.Item>
						)}
					</Index>
				</Rating.Control>
			</Rating>
			<p>Your rating is: {value()}/5</p>
		</>
	);
}

Half Ratings

allowHalf prop을 true로 설정해 0.5 값 단계를 허용할 수 있어요.

<Rating allowHalf>
	<Rating.Control>
		<Index each={Array(5)}>
			{_ => (
				<Rating.Item>
					<Rating.ItemControl>
						{state => (state.half() ? <StarHalfIcon /> : <StarIcon />)}
					</Rating.ItemControl>
				</Rating.Item>
			)}
		</Index>
	</Rating.Control>
</Rating>

Description

Rating.Description 컴포넌트를 사용해 레이팅에 추가 도움말 텍스트를 연결할 수 있어요.

<Rating>
	<Rating.Label>Rate Us:</Rating.Label>
	<Rating.Control>
		<Index each={Array(5)}>
			{_ => (
				<Rating.Item>
					<Rating.ItemControl>
						<StarIcon />
					</Rating.ItemControl>
				</Rating.Item>
			)}
		</Index>
	</Rating.Control>
	<Rating.Description>Rate your experience with us.</Rating.Description>
</Rating>

Error message

Rating.ErrorMessage 컴포넌트를 사용해 사용자가 유효성 검사 오류를 해결하도록 도울 수 있어요. 보조 기술에 레이팅을 의미적으로 유효하지 않음으로 표시하기 위해 validationState prop과 함께 사용해야 해요.

기본적으로 validationState prop이 invalid로 설정된 경우에만 렌더링돼요. 오류 메시지를 항상 렌더링하려면 forceMount prop을 사용해요(ex: 애니메이션 라이브러리와 함께 사용할 때).

import { createSignal } from "solid-js";

function ErrorMessageExample() {
	const [value, setValue] = createSignal(0);

	return (
		<Rating
			value={value()}
			onChange={setValue}
			validationState={value() === 0 ? "invalid" : "valid"}
		>
			<Rating.Label>Rate Us:</Rating.Label>
			<Rating.Control>
				<Index each={Array(5)}>
					{_ => (
						<Rating.Item>
							<Rating.ItemControl>
								<StarIcon />
							</Rating.ItemControl>
						</Rating.Item>
					)}
				</Index>
			</Rating.Control>
			<Rating.ErrorMessage>Please select a rating between 1 and 5.</Rating.ErrorMessage>
		</Rating>
	);
}

HTML forms

name prop을 사용해 HTML 폼과 통합할 수 있어요.

function HTMLFormExample() {
	const onSubmit = (e: SubmitEvent) => {
		// handle form submission.
	};

	return (
		<form onSubmit={onSubmit}>
			<Rating name="rate">
				<Rating.Control>
					<Index each={Array(5)}>
						{_ => (
							<Rating.Item>
								<Rating.ItemControl>
									<StarIcon />
								</Rating.ItemControl>
							</Rating.Item>
						)}
					</Index>
				</Rating.Control>
				<Rating.HiddenInput />
			</Rating>
			<div>
				<button type="reset">Reset</button>
				<button type="submit">Submit</button>
			</div>
		</form>
	);
}

API Reference

Rating

Rating은 @kobalte/core/rating의 Root import와 동일해요.

Prop Description
value number
The current rating value.
defaultValue number
The initial value of the rating when it is first rendered. Use when you do not need to control the state of the rating.
onChange (value: number) => void
Event handler called when the value changes.
allowHalf boolean
Whether to allow half ratings.
orientation 'horizontal' | 'vertical'
The axis the rating items should align with.
name string
The name of the rating. Submitted with its owning form as part of a name/value pair.
validationState 'valid' | 'invalid'
Whether the rating should display its "valid" or "invalid" visual styling.
required boolean
Whether the user must select an item before the owning form can be submitted.
disabled boolean
Whether the rating is disabled.
readOnly boolean
Whether the rating items can be selected but not changed by the user.
Data attribute Description
data-valid Present when the rating is valid according to the validation rules.
data-invalid Present when the rating is invalid according to the validation rules.
data-required Present when the user must select a rating item before the owning form can be submitted.
data-disabled Present when the rating is disabled.
data-readonly Present when the rating is read only.

Rating.Label, Rating.Description and Rating.ErrorMesssage shares the same data-attributes.

Rating.ErrorMessage

Prop Description
forceMount boolean
Used to force mounting when more control is needed. Useful when controlling animation with SolidJS animation libraries.

Rating.ItemControl

Render Prop Description
half Accessor<boolean>
Whether the rating item is half.
highlighted Accessor<boolean>
Whether the rating item is highlighted.
Data attribute Description
data-valid Present when the parent rating is valid according to the validation rules.
data-invalid Present when the parent rating is invalid according to the validation rules.
data-required Present when the parent rating is required.
data-disabled Present when the parent rating is disabled.
data-readonly Present when the parent rating is read only.
data-checked Present when the rating is checked.
data-half Present when the rating is half.
data-highlighted Present when the rating is highlighted.

Rating.ItemLabel and Rating.ItemDescription share the same data-attributes.

Rendered elements

Component Default rendered element
Rating div
Rating.Control div
Rating.Label span
Rating.HiddenInput input
Rating.Description div
Rating.ErrorMessage div
Rating.Item div
Rating.ItemControl div
Rating.ItemLabel label
Rating.ItemDescription div

Accessibility

Keyboard Interactions

Key Description
ArrowDown Moves focus to the next item, increasing the rating value based on the allowHalf property.
ArrowRight Moves focus to the next item, increasing the rating value based on the allowHalf property.
ArrowUp Moves focus to the previous item, decreasing the rating value based on the allowHalf property.
ArrowLeft Moves focus to the previous item, decreasing the rating value based on the allowHalf property.
Space Selects the focused item in the rating.
Home Sets the value of the rating to 1.
End Sets the value of the rating to the maximum value.

더 알아보기 (Learn more)