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

Radio Group

원문 보기 위키 갱신

일련의 라디오 버튼에 공유 상태를 제공하는 품질 높은 비스타일(unstyled) React 라디오 그룹 컴포넌트예요.

출처: Base UI Radio Group

본문

일련의 라디오 버튼에 공유 상태를 제공하는 품질이 높고 비스타일인 React 라디오 그룹 컴포넌트예요.

데모 (Demo)

Tailwind

이 예시는 Tailwind CSS로 컴포넌트를 구현하는 방법을 보여줘요.

/* index.tsx */
'use client';
import * as React from 'react';
import { Radio } from '@base-ui/react/radio';
import { RadioGroup } from '@base-ui/react/radio-group';

export default function ExampleRadioGroup() {
  const id = React.useId();
  return (
    <RadioGroup
      aria-labelledby={id}
      defaultValue="fuji-apple"
      className="flex flex-col items-start gap-1 text-neutral-950 dark:text-white"
    >
      <div className="text-sm font-bold" id={id}>
        Best apple
      </div>

      <label className="flex items-center gap-2 text-sm font-normal text-neutral-950 dark:text-white">
        <Radio.Root
          value="fuji-apple"
          className="flex size-4 shrink-0 items-center justify-center border rounded-full p-0 border-neutral-950 bg-white text-white dark:border-white dark:bg-neutral-950 dark:text-neutral-950 data-checked:bg-neutral-950 data-checked:text-white dark:data-checked:bg-white dark:data-checked:text-neutral-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-950 dark:focus-visible:outline-white"
        >
          <Radio.Indicator className="flex items-center justify-center data-unchecked:hidden before:size-2 before:rounded-full before:bg-current" />
        </Radio.Root>
        Fuji
      </label>

      <label className="flex items-center gap-2 text-sm font-normal text-neutral-950 dark:text-white">
        <Radio.Root
          value="gala-apple"
          className="flex size-4 shrink-0 items-center justify-center border rounded-full p-0 border-neutral-950 bg-white text-white dark:border-white dark:bg-neutral-950 dark:text-neutral-950 data-checked:bg-neutral-950 data-checked:text-white dark:data-checked:bg-white dark:data-checked:text-neutral-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-950 dark:focus-visible:outline-white"
        >
          <Radio.Indicator className="flex items-center justify-center data-unchecked:hidden before:size-2 before:rounded-full before:bg-current" />
        </Radio.Root>
        Gala
      </label>

      <label className="flex items-center gap-2 text-sm font-normal text-neutral-950 dark:text-white">
        <Radio.Root
          value="granny-smith-apple"
          className="flex size-4 shrink-0 items-center justify-center border rounded-full p-0 border-neutral-950 bg-white text-white dark:border-white dark:bg-neutral-950 dark:text-neutral-950 data-checked:bg-neutral-950 data-checked:text-white dark:data-checked:bg-white dark:data-checked:text-neutral-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-950 dark:focus-visible:outline-white"
        >
          <Radio.Indicator className="flex items-center justify-center data-unchecked:hidden before:size-2 before:rounded-full before:bg-current" />
        </Radio.Root>
        Granny Smith
      </label>
    </RadioGroup>
  );
}

CSS Modules

이 예시는 CSS Modules로 컴포넌트를 구현하는 방법을 보여줘요.

/* index.module.css */
.RadioGroup {
  display: flex;
  flex-direction: column;
  align-items: start;
  gap: 0.25rem;
  color: oklch(14.5% 0 0deg);

  @media (prefers-color-scheme: dark) {
    color: white;
  }
}

.Caption {
  font-size: 0.875rem;
  line-height: 1.25rem;
  font-weight: 700;
}

.Item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.875rem;
  line-height: 1.25rem;
  font-weight: 400;
}

.Radio {
  box-sizing: border-box;
  display: flex;
  flex-shrink: 0;
  width: 1rem;
  height: 1rem;
  align-items: center;
  justify-content: center;
  border: 1px solid oklch(14.5% 0 0deg);
  border-radius: 100%;
  background-color: white;
  color: white;
  padding: 0;
  margin: 0;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
    color: oklch(14.5% 0 0deg);
  }

  &[data-checked] {
    background-color: oklch(14.5% 0 0deg);
    color: white;

    @media (prefers-color-scheme: dark) {
      background-color: white;
      color: oklch(14.5% 0 0deg);
    }
  }

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: 2px;

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}

.Indicator {
  display: flex;
  align-items: center;
  justify-content: center;

  &[data-unchecked] {
    display: none;
  }

  &::before {
    content: '';
    border-radius: 100%;
    width: 0.5rem;
    height: 0.5rem;
    background-color: currentcolor;
  }
}
/* index.tsx */
'use client';
import * as React from 'react';
import { Radio } from '@base-ui/react/radio';
import { RadioGroup } from '@base-ui/react/radio-group';
import styles from './index.module.css';

export default function ExampleRadioGroup() {
  const id = React.useId();
  return (
    <RadioGroup aria-labelledby={id} defaultValue="fuji-apple" className={styles.RadioGroup}>
      <div className={styles.Caption} id={id}>
        Best apple
      </div>

      <label className={styles.Item}>
        <Radio.Root value="fuji-apple" className={styles.Radio}>
          <Radio.Indicator className={styles.Indicator} />
        </Radio.Root>
        Fuji
      </label>

      <label className={styles.Item}>
        <Radio.Root value="gala-apple" className={styles.Radio}>
          <Radio.Indicator className={styles.Indicator} />
        </Radio.Root>
        Gala
      </label>

      <label className={styles.Item}>
        <Radio.Root value="granny-smith-apple" className={styles.Radio}>
          <Radio.Indicator className={styles.Indicator} />
        </Radio.Root>
        Granny Smith
      </label>
    </RadioGroup>
  );
}

사용 가이드라인 (Usage guidelines)

구조 (Anatomy)

컴포넌트를 임포트해서 파트를 조립해요:

import { Radio } from '@base-ui/react/radio';
import { RadioGroup } from '@base-ui/react/radio-group';

<RadioGroup>
  <Radio.Root>
    <Radio.Indicator />
  </Radio.Root>
</RadioGroup>;

예시 (Examples)

라디오 그룹에 라벨 지정하기

aria-labelledby와 형제 라벨 요소로 그룹에 라벨을 지정해요:

<div id="storage-type-label">Storage type</div>
<RadioGroup aria-labelledby="storage-type-label">{/* ... */}</RadioGroup>

각 라디오에 가장 간단한 라벨링 패턴은 감싸는 <label>이에요:

// @highlight
<label>
  <Radio.Root value="ssd" />
  SSD
  {/* @highlight */}
</label>

네이티브 버튼으로 렌더링하기

기본적으로 <Radio.Root>는 감싸는 라벨을 지원하기 위해 <span> 요소를 렌더링해요. 형제 라벨(htmlFor/id)을 쓸 때는 각 라디오를 네이티브 버튼으로 렌더링하는 것을 권장해요.

<div id="storage-type">Storage type</div>
<RadioGroup defaultValue="ssd" aria-labelledby="storage-type">
  <div>
    <label htmlFor="storage-type-ssd">SSD</label>
    {/* @highlight-text "nativeButton" "render={<button />}" */}
    <Radio.Root value="ssd" id="storage-type-ssd" nativeButton render={<button />}>
      <Radio.Indicator />
    </Radio.Root>
  </div>
</RadioGroup>

감싸는 라벨이 있는 네이티브 버튼은 render 콜백을 사용해 유효하지 않은 HTML을 피함으로써 지원돼요. 그래서 숨겨진 input은 라벨 밖에 배치돼요:

<div id="storage-type">Storage type</div>
<RadioGroup defaultValue="ssd" aria-labelledby="storage-type">
  <Radio.Root
    value="ssd"
    nativeButton
    // @highlight-start
    render={(buttonProps) => (
      <label>
        <button {...buttonProps} />
        SSD
      </label>
    )}
    {/* @highlight-end */}
  />
</RadioGroup>

폼 통합 (Form integration)

그룹 라벨링과 폼 통합에는 Field와 Fieldset을 사용해요:

<Form>
  {/* @highlight */}
  <Field.Root name="storageType">
    <Fieldset.Root render={<RadioGroup />}>
      <Fieldset.Legend>Storage type</Fieldset.Legend>
      <Field.Item>
        <Field.Label>
          <Radio.Root value="ssd" />
          SSD
        </Field.Label>
      </Field.Item>
      <Field.Item>
        <Field.Label>
          <Radio.Root value="hdd" />
          HDD
        </Field.Label>
      </Field.Item>
    </Fieldset.Root>
  </Field.Root>
</Form>

API 레퍼런스

RadioGroup

Root

라디오 버튼 자체를 나타내요. <span> 요소와 그 옆에 숨겨진 <input>을 렌더링해요.

Root Props:

Prop Type Default Description
value* Value - 그룹에서 라디오를 식별하는 고유한 값이에요.
nativeButton boolean false render prop을 통해 요소를 대체할 때 네이티브 <button> 요소를 렌더링할지 여부예요. 렌더링되는 요소가 네이티브 버튼이면 true로 설정해요.
disabled boolean - 컴포넌트가 사용자 상호작용을 무시할지 여부예요.
readOnly boolean - 사용자가 라디오 버튼을 선택할 수 없어야 하는지 여부예요.
required boolean - 사용자가 폼을 제출하기 전에 값을 선택해야 하는지 여부예요.
inputRef React.Ref<HTMLInputElement> - 숨겨진 input 요소에 접근하는 ref예요.
className string | ((state: Radio.Root.State) => string | undefined) - 요소에 적용되는 CSS 클래스이거나, 컴포넌트 상태에 따라 클래스를 반환하는 함수예요.
style React.CSSProperties | ((state: Radio.Root.State) => React.CSSProperties | undefined) - 요소에 적용되는 스타일이거나, 컴포넌트 상태에 따라 스타일 객체를 반환하는 함수예요.
render ReactElement | ((props: HTMLProps, state: Radio.Root.State) => ReactElement) - 컴포넌트의 HTML 요소를 다른 태그로 바꾸거나 다른 컴포넌트와 합성할 수 있게 해줘요. 렌더링할 요소를 반환하는 ReactElement나 함수를 받아요.

Root Data Attributes:

Attribute Type Description
data-checked - 라디오가 체크되어 있을 때 나타나요.
data-unchecked - 라디오가 체크되지 않았을 때 나타나요.
data-disabled - 라디오가 비활성화되어 있을 때 나타나요.
data-readonly - 라디오가 읽기 전용일 때 나타나요.
data-required - 라디오가 필수일 때 나타나요.
data-valid - 라디오가 유효한 상태일 때 나타나요 (Field.Root로 감싸져 있을 때).
data-invalid - 라디오가 유효하지 않은 상태일 때 나타나요 (Field.Root로 감싸져 있을 때).
data-dirty - 라디오의 값이 변경되었을 때 나타나요 (Field.Root로 감싸져 있을 때).
data-touched - 라디오가 터치되었을 때 나타나요 (Field.Root로 감싸져 있을 때).
data-filled - 라디오가 체크되어 있을 때 나타나요 (Field.Root로 감싸져 있을 때).
data-focused - 라디오에 포커스되어 있을 때 나타나요 (Field.Root로 감싸져 있을 때).

Root.Props

Root props의 재수출이에요.

Root.State

type RadioRootState = {
  /** Whether the radio button is currently selected. */
  checked: boolean;
  /** Whether the component should ignore user interaction. */
  disabled: boolean;
  /** Whether the user should be unable to select the radio button. */
  readOnly: boolean;
  /** Whether the user must choose a value before submitting a form. */
  required: boolean;
  /** Whether the radio button has been touched (when wrapped in Field.Root). */
  touched: boolean;
  /** Whether the radio button's value has changed from its initial value (when wrapped in Field.Root). */
  dirty: boolean;
  /** Whether the radio button is in a valid state (when wrapped in Field.Root). */
  valid: boolean | null;
  /** Whether the radio button has a value (when wrapped in Field.Root). */
  filled: boolean;
  /** Whether the radio button is focused (when wrapped in Field.Root). */
  focused: boolean;
};

Indicator

라디오 버튼이 선택되었는지 나타내요. <span> 요소를 렌더링해요.

Indicator Props:

Prop Type Default Description
className string | ((state: Radio.Indicator.State) => string | undefined) - 요소에 적용되는 CSS 클래스이거나, 컴포넌트 상태에 따라 클래스를 반환하는 함수예요.
style React.CSSProperties | ((state: Radio.Indicator.State) => React.CSSProperties | undefined) - 요소에 적용되는 스타일이거나, 컴포넌트 상태에 따라 스타일 객체를 반환하는 함수예요.
keepMounted boolean false 라디오 버튼이 비활성 상태일 때 HTML 요소를 DOM에 유지할지 여부예요.
render ReactElement | ((props: HTMLProps, state: Radio.Indicator.State) => ReactElement) - 컴포넌트의 HTML 요소를 다른 태그로 바꾸거나 다른 컴포넌트와 합성할 수 있게 해줘요. 렌더링할 요소를 반환하는 ReactElement나 함수를 받아요.

Indicator Data Attributes:

Attribute Type Description
data-checked - 라디오가 체크되어 있을 때 나타나요.
data-unchecked - 라디오가 체크되지 않았을 때 나타나요.
data-disabled - 라디오가 비활성화되어 있을 때 나타나요.
data-readonly - 라디오가 읽기 전용일 때 나타나요.
data-required - 라디오가 필수일 때 나타나요.
data-valid - 라디오가 유효한 상태일 때 나타나요 (Field.Root로 감싸져 있을 때).
data-invalid - 라디오가 유효하지 않은 상태일 때 나타나요 (Field.Root로 감싸져 있을 때).
data-dirty - 라디오의 값이 변경되었을 때 나타나요 (Field.Root로 감싸져 있을 때).
data-touched - 라디오가 터치되었을 때 나타나요 (Field.Root로 감싸져 있을 때).
data-filled - 라디오가 체크되어 있을 때 나타나요 (Field.Root로 감싸져 있을 때).
data-focused - 라디오에 포커스되어 있을 때 나타나요 (Field.Root로 감싸져 있을 때).
data-starting-style - 라디오 인디케이터가 들어오는 애니메이션을 시작할 때 나타나요.
data-ending-style - 라디오 인디케이터가 나가는 애니메이션 중일 때 나타나요.

Indicator.Props

Indicator props의 재수출이에요.

Indicator.State

type RadioIndicatorState = {
  /** The transition status of the component. */
  transitionStatus: TransitionStatus;
  /** Whether the radio button is currently selected. */
  checked: boolean;
  /** Whether the component should ignore user interaction. */
  disabled: boolean;
  /** Whether the user should be unable to select the radio button. */
  readOnly: boolean;
  /** Whether the user must choose a value before submitting a form. */
  required: boolean;
  /** Whether the radio button has been touched (when wrapped in Field.Root). */
  touched: boolean;
  /** Whether the radio button's value has changed from its initial value (when wrapped in Field.Root). */
  dirty: boolean;
  /** Whether the radio button is in a valid state (when wrapped in Field.Root). */
  valid: boolean | null;
  /** Whether the radio button has a value (when wrapped in Field.Root). */
  filled: boolean;
  /** Whether the radio button is focused (when wrapped in Field.Root). */
  focused: boolean;
};

RadioGroup

일련의 라디오 버튼에 공유 상태를 제공해요. <div> 요소를 렌더링해요.

RadioGroup Props:

Prop Type Default Description
name string - 폼이 제출될 때 필드를 식별해요.
defaultValue Value - 처음에 선택되어야 할 라디오 버튼의 비제어 값이에요. 제어형 라디오 그룹을 렌더링하려면 대신 value prop을 사용해요.
value Value - 현재 선택되어야 할 라디오 항목의 제어 값이에요. 비제어형 라디오 그룹을 렌더링하려면 대신 defaultValue prop을 사용해요.
onValueChange ((value: Value, eventDetails: RadioGroup.ChangeEventDetails) => void) - 값이 변경될 때 호출되는 콜백이에요.
form string - 라디오 input을 소유하는 폼을 식별해요. 라디오 그룹이 폼 바깥에 렌더링될 때 유용해요.
disabled boolean false 컴포넌트가 사용자 상호작용을 무시할지 여부예요.
readOnly boolean false 사용자가 그룹에서 다른 라디오 버튼을 선택할 수 없어야 하는지 여부예요.
required boolean false 사용자가 폼을 제출하기 전에 값을 선택해야 하는지 여부예요.
inputRef React.Ref<HTMLInputElement> - 숨겨진 input 요소에 접근하는 ref예요.
className string | ((state: RadioGroup.State) => string | undefined) - 요소에 적용되는 CSS 클래스이거나, 컴포넌트 상태에 따라 클래스를 반환하는 함수예요.
style React.CSSProperties | ((state: RadioGroup.State) => React.CSSProperties | undefined) - 요소에 적용되는 스타일이거나, 컴포넌트 상태에 따라 스타일 객체를 반환하는 함수예요.
render ReactElement | ((props: HTMLProps, state: RadioGroup.State) => ReactElement) - 컴포넌트의 HTML 요소를 다른 태그로 바꾸거나 다른 컴포넌트와 합성할 수 있게 해줘요. 렌더링할 요소를 반환하는 ReactElement나 함수를 받아요.

RadioGroup Data Attributes:

Attribute Type Description
data-disabled - 라디오 그룹이 비활성화되어 있을 때 나타나요.

RadioGroup.Props

RadioGroup props의 재수출이에요.

RadioGroup.State

type RadioGroupState = {
  /** Whether the user should be unable to select a different radio button in the group. */
  readOnly: boolean;
  /** Whether the user must tick a radio button within the group before submitting a form. */
  required: boolean;
  /** Whether the component should ignore user interaction. */
  disabled: boolean;
  /** Whether the field has been touched. */
  touched: boolean;
  /** Whether the field value has changed from its initial value. */
  dirty: boolean;
  /** Whether the field is valid. */
  valid: boolean | null;
  /** Whether the field has a value. */
  filled: boolean;
  /** Whether the field is focused. */
  focused: boolean;
};

RadioGroup.ChangeEventReason

type RadioGroupChangeEventReason = 'none';

RadioGroup.ChangeEventDetails

type RadioGroupChangeEventDetails = {
  /** The reason for the event. */
  reason: 'none';
  /** The native event associated with the custom event. */
  event: Event;
  /** Cancels Base UI from handling the event. */
  cancel: () => void;
  /** Allows the event to propagate in cases where Base UI will stop the propagation. */
  allowPropagation: () => void;
  /** Indicates whether the event has been canceled. */
  isCanceled: boolean;
  /** Indicates whether the event is allowed to propagate. */
  isPropagationAllowed: boolean;
  /** The element that triggered the event, if applicable. */
  trigger: Element | undefined;
};

추가 타입 (Additional Types)

RadioIndicatorProps

type RadioIndicatorProps = {
  /**
   * Whether to keep the HTML element in the DOM when the radio button is inactive.
   * @default false
   */
  keepMounted?: boolean;
  /**
   * CSS class applied to the element, or a function that
   * returns a class based on the component's state.
   */
  className?: string | ((state: Radio.Indicator.State) => string | undefined);
  /**
   * Allows you to replace the component's HTML element
   * with a different tag, or compose it with another component.
   *
   * Accepts a `ReactElement` or a function that returns the element to render.
   */
  render?: ReactElement | ((props: HTMLProps, state: Radio.Indicator.State) => ReactElement);
  /**
   * Style applied to the element, or a function that
   * returns a style object based on the component's state.
   */
  style?: React.CSSProperties | ((state: Radio.Indicator.State) => React.CSSProperties | undefined);
};

RadioIndicatorState

type RadioIndicatorState = {
  /** The transition status of the component. */
  transitionStatus: TransitionStatus;
  /** Whether the radio button is currently selected. */
  checked: boolean;
  /** Whether the component should ignore user interaction. */
  disabled: boolean;
  /** Whether the user should be unable to select the radio button. */
  readOnly: boolean;
  /** Whether the user must choose a value before submitting a form. */
  required: boolean;
  /** Whether the radio button has been touched (when wrapped in Field.Root). */
  touched: boolean;
  /** Whether the radio button's value has changed from its initial value (when wrapped in Field.Root). */
  dirty: boolean;
  /** Whether the radio button is in a valid state (when wrapped in Field.Root). */
  valid: boolean | null;
  /** Whether the radio button has a value (when wrapped in Field.Root). */
  filled: boolean;
  /** Whether the radio button is focused (when wrapped in Field.Root). */
  focused: boolean;
};

RadioRootProps

type RadioRootProps<Value = any> = {
  /** The unique identifying value of the radio in a group. */
  value: Value;
  /** Whether the component should ignore user interaction. */
  disabled?: boolean;
  /** Whether the user must choose a value before submitting a form. */
  required?: boolean;
  /** Whether the user should be unable to select the radio button. */
  readOnly?: boolean;
  /** A ref to access the hidden input element. */
  inputRef?: React.Ref<HTMLInputElement>;
  /**
   * Whether the component renders a native `<button>` element when replacing it
   * via the `render` prop.
   * Set to `true` if the rendered element is a native button.
   * @default false
   */
  nativeButton?: boolean;
  /**
   * CSS class applied to the element, or a function that
   * returns a class based on the component's state.
   */
  className?: string | ((state: Radio.Root.State) => string | undefined);
  /**
   * Style applied to the element, or a function that
   * returns a style object based on the component's state.
   */
  style?: React.CSSProperties | ((state: Radio.Root.State) => React.CSSProperties | undefined);
  /**
   * Allows you to replace the component's HTML element
   * with a different tag, or compose it with another component.
   *
   * Accepts a `ReactElement` or a function that returns the element to render.
   */
  render?: ReactElement | ((props: HTMLProps, state: Radio.Root.State) => ReactElement);
};

RadioRootState

type RadioRootState = {
  /** Whether the radio button is currently selected. */
  checked: boolean;
  /** Whether the component should ignore user interaction. */
  disabled: boolean;
  /** Whether the user should be unable to select the radio button. */
  readOnly: boolean;
  /** Whether the user must choose a value before submitting a form. */
  required: boolean;
  /** Whether the radio button has been touched (when wrapped in Field.Root). */
  touched: boolean;
  /** Whether the radio button's value has changed from its initial value (when wrapped in Field.Root). */
  dirty: boolean;
  /** Whether the radio button is in a valid state (when wrapped in Field.Root). */
  valid: boolean | null;
  /** Whether the radio button has a value (when wrapped in Field.Root). */
  filled: boolean;
  /** Whether the radio button is focused (when wrapped in Field.Root). */
  focused: boolean;
};

Export Groups

  • RadioGroup: RadioGroup, RadioGroup.State, RadioGroup.Props, RadioGroup.ChangeEventReason, RadioGroup.ChangeEventDetails, RadioGroupState, RadioGroupProps, RadioGroupChangeEventReason, RadioGroupChangeEventDetails
  • Radio: Radio.Root, Radio.Root.State, Radio.Root.Props, Radio.Indicator, Radio.Indicator.Props, Radio.Indicator.State, RadioRootState, RadioRootProps, RadioIndicatorProps, RadioIndicatorState

Canonical Types

Canonical: Alias 매핑 — 네임스페이스가 이미 임포트되어 있으면 Canonical을, 그렇지 않으면 Alias를 사용해요.

  • RadioGroup.State (RadioGroup): RadioGroupState
  • RadioGroup.Props (RadioGroup): RadioGroupProps
  • RadioGroup.ChangeEventReason (RadioGroup): RadioGroupChangeEventReason
  • RadioGroup.ChangeEventDetails (RadioGroup): RadioGroupChangeEventDetails

더 알아보기 (Learn more)