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

Rating Group

원문 보기 위키 갱신

Rating Group (평점 그룹)

사용자가 아이콘의 집합을 통해 항목을 평가할 수 있게 해주는 컴포넌트예요. 별점 같은 아이콘을 눌러 점수를 매기거나, 호버로 미리 점수를 표시할 수 있어요.

출처: 문서

본문

구조 (Anatomy)

평점 그룹의 기본 구조는 다음과 같아요. Root 안에 Label, Control, 그리고 각 별점 Item들을 배치해요.

<RatingGroup.Root>
  <RatingGroup.Label />
  <RatingGroup.Control>
    <RatingGroup.Item>
      <RatingGroup.ItemContext />
    </RatingGroup.Item>
    <RatingGroup.HiddenInput />
  </RatingGroup.Control>
</RatingGroup.Root>

예제 (Examples)

기본 (Basic)

defaultValue로 기본 점수를 지정해요. 각 RatingGroup.Item의 index prop으로 별점 순서를 정해요.

import { RatingGroup } from '@ark-ui/react/rating-group'
import { StarIcon } from 'lucide-react'
import styles from 'styles/rating-group.module.css'

export const Basic = () => (
  <RatingGroup.Root className={styles.Root} defaultValue={3}>
    <RatingGroup.Label className={styles.Label}>Label</RatingGroup.Label>
    <RatingGroup.Control className={styles.Control}>
      <RatingGroup.Context>
        {({ items }) =>
          items.map((item) => (
            <RatingGroup.Item className={styles.Item} key={item} index={item}>
              <RatingGroup.ItemContext>
                {({ highlighted }) => (
                  <span className={styles.ItemIndicator} data-highlighted={highlighted ? '' : undefined}>
                    <StarIcon data-bg="" />
                    <StarIcon data-fg="" fill="currentColor" />
                  </span>
                )}
              </RatingGroup.ItemContext>
            </RatingGroup.Item>
          ))
        }
      </RatingGroup.Context>
      <RatingGroup.HiddenInput />
    </RatingGroup.Control>
  </RatingGroup.Root>
)

제어된 방식 (Controlled)

RatingGroup 컴포넌트를 사용할 때는 value와 onValueChange prop으로 상태를 제어할 수 있어요.

import { RatingGroup } from '@ark-ui/react/rating-group'
import { StarIcon } from 'lucide-react'
import { useState } from 'react'
import styles from 'styles/rating-group.module.css'

export const Controlled = () => {
  const [value, setValue] = useState(0)

  return (
    <RatingGroup.Root className={styles.Root} value={value} onValueChange={(details) => setValue(details.value)}>
      <RatingGroup.Label className={styles.Label}>Label</RatingGroup.Label>
      <RatingGroup.Control className={styles.Control}>
        <RatingGroup.Context>
          {({ items }) =>
            items.map((item) => (
              <RatingGroup.Item className={styles.Item} key={item} index={item}>
                <RatingGroup.ItemContext>
                  {({ half, highlighted }) => (
                    <span
                      className={styles.ItemIndicator}
                      data-half={half ? '' : undefined}
                      data-highlighted={highlighted ? '' : undefined}
                    >
                      <StarIcon data-bg="" />
                      <StarIcon data-fg="" fill="currentColor" />
                    </span>
                  )}
                </RatingGroup.ItemContext>
              </RatingGroup.Item>
            ))
          }
        </RatingGroup.Context>
        <RatingGroup.HiddenInput />
      </RatingGroup.Control>
    </RatingGroup.Root>
  )
}

루트 프로바이더 (Root Provider)

평점 그룹을 제어하는 또 다른 방법은 RootProvider 컴포넌트와 useRatingGroup 훅을 사용하는 거예요. 이렇게 하면 컴포넌트 밖에서 상태와 메서드에 접근할 수 있어요.

import { RatingGroup, useRatingGroup } from '@ark-ui/react/rating-group'
import { StarIcon } from 'lucide-react'
import styles from 'styles/rating-group.module.css'

export const RootProvider = () => {
  const ratingGroup = useRatingGroup({ count: 5, defaultValue: 3 })

  return (
    <div className="stack">
      <output>value: {ratingGroup.value}</output>
      <RatingGroup.RootProvider className={styles.Root} value={ratingGroup}>
        <RatingGroup.Label className={styles.Label}>Label</RatingGroup.Label>
        <RatingGroup.Control className={styles.Control}>
          <RatingGroup.Context>
            {({ items }) =>
              items.map((item) => (
                <RatingGroup.Item className={styles.Item} key={item} index={item}>
                  <RatingGroup.ItemContext>
                    {({ highlighted }) => (
                      <span className={styles.ItemIndicator} data-highlighted={highlighted ? '' : undefined}>
                        <StarIcon data-bg="" />
                        <StarIcon data-fg="" fill="currentColor" />
                      </span>
                    )}
                  </RatingGroup.ItemContext>
                </RatingGroup.Item>
              ))
            }
          </RatingGroup.Context>
          <RatingGroup.HiddenInput />
        </RatingGroup.Control>
      </RatingGroup.RootProvider>
    </div>
  )
}

Field 함께 사용하기 (Field)

Field 컴포넌트는 평점 그룹의 폼 관련 상태와 접근성 속성을 관리할 수 있게 도와줘요. ARIA 라벨, 도우미 텍스트, 오류 텍스트 처리를 포함해서 올바른 접근성을 보장해요.

import { Field } from '@ark-ui/react/field'
import { RatingGroup } from '@ark-ui/react/rating-group'
import { StarIcon } from 'lucide-react'
import field from 'styles/field.module.css'
import styles from 'styles/rating-group.module.css'

export const WithField = () => (
  <Field.Root className={field.Root}>
    <RatingGroup.Root className={styles.Root} count={5} defaultValue={3}>
      <RatingGroup.Label className={styles.Label}>Label</RatingGroup.Label>
      <RatingGroup.Control className={styles.Control}>
        <RatingGroup.Context>
          {({ items }) =>
            items.map((item) => (
              <RatingGroup.Item className={styles.Item} key={item} index={item}>
                <RatingGroup.ItemContext>
                  {({ highlighted }) => (
                    <span className={styles.ItemIndicator} data-highlighted={highlighted ? '' : undefined}>
                      <StarIcon data-bg="" />
                      <StarIcon data-fg="" fill="currentColor" />
                    </span>
                  )}
                </RatingGroup.ItemContext>
              </RatingGroup.Item>
            ))
          }
        </RatingGroup.Context>
        <RatingGroup.HiddenInput />
      </RatingGroup.Control>
    </RatingGroup.Root>
    <Field.HelperText className={field.HelperText}>Additional Info</Field.HelperText>
    <Field.ErrorText className={field.ErrorText}>Error Info</Field.ErrorText>
  </Field.Root>
)

반쪽 평점 (Half Rating)

allowHalf prop을 true로 설정하면 0.5 값 단위를 허용할 수 있어요. Rating 컴포넌트의 렌더 콜백에서 half 값이 설정된 경우 올바른 아이콘을 렌더링하도록 해야 해요.

import { RatingGroup } from '@ark-ui/react/rating-group'
import { StarIcon } from 'lucide-react'
import styles from 'styles/rating-group.module.css'

export const HalfStar = () => (
  <RatingGroup.Root className={styles.Root} defaultValue={2.5} allowHalf>
    <RatingGroup.Label className={styles.Label}>Label</RatingGroup.Label>
    <RatingGroup.Control className={styles.Control}>
      <RatingGroup.Context>
        {({ items }) =>
          items.map((item) => (
            <RatingGroup.Item className={styles.Item} key={item} index={item}>
              <RatingGroup.ItemContext>
                {({ half, highlighted }) => (
                  <span
                    className={styles.ItemIndicator}
                    data-half={half ? '' : undefined}
                    data-highlighted={highlighted ? '' : undefined}
                  >
                    <StarIcon data-bg="" />
                    <StarIcon data-fg="" fill="currentColor" />
                  </span>
                )}
              </RatingGroup.ItemContext>
            </RatingGroup.Item>
          ))
        }
      </RatingGroup.Context>
      <RatingGroup.HiddenInput />
    </RatingGroup.Control>
  </RatingGroup.Root>
)

폼 사용 (Forms)

폼 안에서 평점 그룹을 사용하려면 name prop을 전달해요. 그러면 숨겨진 input이 렌더링되고 값 변경이 폼에 올바르게 전달되도록 보장해요.

import { RatingGroup } from '@ark-ui/react/rating-group'
import { StarIcon } from 'lucide-react'
import styles from 'styles/rating-group.module.css'
import button from 'styles/button.module.css'

export const FormUsage = () => (
  <form
    className="stack"
    onSubmit={(e) => {
      e.preventDefault()
      const formData = new FormData(e.currentTarget)
      alert(`Rating value: ${formData.get('review')}`)
    }}
  >
    <RatingGroup.Root className={styles.Root} name="review" defaultValue={3}>
      <RatingGroup.Label className={styles.Label}>Label</RatingGroup.Label>
      <RatingGroup.Control className={styles.Control}>
        <RatingGroup.Context>
          {({ items }) =>
            items.map((item) => (
              <RatingGroup.Item className={styles.Item} key={item} index={item}>
                <RatingGroup.ItemContext>
                  {({ highlighted }) => (
                    <span className={styles.ItemIndicator} data-highlighted={highlighted ? '' : undefined}>
                      <StarIcon data-bg="" />
                      <StarIcon data-fg="" fill="currentColor" />
                    </span>
                  )}
                </RatingGroup.ItemContext>
              </RatingGroup.Item>
            ))
          }
        </RatingGroup.Context>
        <RatingGroup.HiddenInput />
      </RatingGroup.Control>
    </RatingGroup.Root>
    <button type="submit" className={button.Root}>
      Submit
    </button>
  </form>
)

비활성화 (Disabled)

평점 그룹을 비활성화하려면 disabled prop을 true로 설정해요.

import { RatingGroup } from '@ark-ui/react/rating-group'
import { StarIcon } from 'lucide-react'
import styles from 'styles/rating-group.module.css'

export const Disabled = () => (
  <RatingGroup.Root className={styles.Root} defaultValue={3} disabled>
    <RatingGroup.Label className={styles.Label}>Label</RatingGroup.Label>
    <RatingGroup.Control className={styles.Control}>
      <RatingGroup.Context>
        {({ items }) =>
          items.map((item) => (
            <RatingGroup.Item className={styles.Item} key={item} index={item}>
              <RatingGroup.ItemContext>
                {({ highlighted }) => (
                  <span className={styles.ItemIndicator} data-highlighted={highlighted ? '' : undefined}>
                    <StarIcon data-bg="" />
                    <StarIcon data-fg="" fill="currentColor" />
                  </span>
                )}
              </RatingGroup.ItemContext>
            </RatingGroup.Item>
          ))
        }
      </RatingGroup.Context>
      <RatingGroup.HiddenInput />
    </RatingGroup.Control>
  </RatingGroup.Root>
)

API 레퍼런스 (API Reference)

속성 (Props)

Root

Props

allowHalf Type: boolean Required: false Default Value: undefined Description: Whether to allow half stars.

asChild Type: boolean Required: false Default Value: undefined Description: Use the provided child element as the default rendered element, combining their props and behavior.

autoFocus Type: boolean Required: false Default Value: undefined Description: Whether to autofocus the rating.

count Type: number Required: false Default Value: 5 Description: The total number of ratings.

defaultValue Type: number Required: false Default Value: undefined Description: The initial value of the rating when rendered. Use when you don't need to control the value of the rating.

disabled Type: boolean Required: false Default Value: undefined Description: Whether the rating is disabled.

form Type: string Required: false Default Value: undefined Description: The associate form of the underlying input element.

id Type: string Required: false Default Value: undefined Description: The unique identifier of the machine.

ids Type: Partial<{ root: string label: string hiddenInput: string control: string item: (id: string) => string }> Required: false Default Value: undefined Description: The ids of the elements in the rating. Useful for composition.

name Type: string Required: false Default Value: undefined Description: The name attribute of the rating element (used in forms).

onHoverChange Type: (details: HoverChangeDetails) => void Required: false Default Value: undefined Description: Function to be called when the rating value is hovered.

onValueChange Type: (details: ValueChangeDetails) => void Required: false Default Value: undefined Description: Function to be called when the rating value changes.

readOnly Type: boolean Required: false Default Value: undefined Description: Whether the rating is readonly.

required Type: boolean Required: false Default Value: undefined Description: Whether the rating is required.

translations Type: IntlTranslations Required: false Default Value: undefined Description: Specifies the localized strings that identifies the accessibility elements and their states

value Type: number Required: false Default Value: undefined Description: The controlled value of the rating

Control

Props

asChild Type: boolean Required: false Default Value: undefined Description: Use the provided child element as the default rendered element, combining their props and behavior.

데이터 속성 (Data Attributes)

data-scope: rating-group data-part: control data-readonly: Present when read-only data-disabled: Present when disabled

HiddenInput

Props

asChild Type: boolean Required: false Default Value: undefined Description: Use the provided child element as the default rendered element, combining their props and behavior.

Item

Props

index Type: number Required: true Default Value: undefined Description: undefined

asChild Type: boolean Required: false Default Value: undefined Description: Use the provided child element as the default rendered element, combining their props and behavior.

데이터 속성 (Data Attributes)

data-scope: rating-group data-part: item data-disabled: Present when disabled data-readonly: Present when read-only data-checked: Present when checked data-highlighted: Present when highlighted data-half:

Label

Props

asChild Type: boolean Required: false Default Value: undefined Description: Use the provided child element as the default rendered element, combining their props and behavior.

데이터 속성 (Data Attributes)

data-scope: rating-group data-part: label data-disabled: Present when disabled data-required: Present when required

RootProvider

Props

value Type: UseRatingGroupReturn Required: true Default Value: undefined Description: undefined

asChild Type: boolean Required: false Default Value: undefined Description: Use the provided child element as the default rendered element, combining their props and behavior.

컨텍스트 (Context)

API:

Property Type Description
setValue (value: number) => void Sets the value of the rating group
clearValue VoidFunction Clears the value of the rating group
hovering boolean Whether the rating group is being hovered
value number The current value of the rating group
hoveredValue number The value of the currently hovered rating
count number The total number of ratings
items number[] The array of rating values. Returns an array of numbers from 1 to the max value.
getItemState (props: ItemProps) => ItemState Returns the state of a rating item

접근성 (Accessibility)

키보드 지원 (Keyboard Support)

ArrowRight Description: Moves focus to the next star, increasing the rating value based on the allowHalf property.

ArrowLeft Description: Moves focus to the previous star, decreasing the rating value based on the allowHalf property.

Enter Description: Selects the focused star in the rating group.

더 알아보기 (Learn more)