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

라디오 그룹(Radio Group)

원문 보기 위키 갱신

한 번에 하나 이상 체크할 수 없는 체크 가능한 버튼(라디오 버튼) 모음으로, 동시에 최대 하나의 버튼만 체크할 수 있어요.

출처: 문서

본문

Import

import { RadioGroup } from "@kobalte/core/radio-group";
// or
import { Root, Label, ... } from "@kobalte/core/radio-group";
// or (deprecated)
import { RadioGroup } from "@kobalte/core";

Features

  • WAI-ARIA Radio Group 디자인 패턴을 따라요.
  • 각 라디오는 시각적으로 숨겨진 네이티브 HTML <input> 요소로 만들어져 커스텀 스타일링을 할 수 있어요.
  • 폼 리셋 이벤트와 동기화돼요.
  • 보조 기술을 위한 그룹 및 라디오 라벨링을 지원해요.
  • 제어(controlled) 또는 비제어(uncontrolled) 방식으로 사용할 수 있어요.

Anatomy

라디오 그룹은 다음 요소들로 구성돼요:

  • RadioGroup: 라디오 그룹의 루트 컨테이너예요.
  • RadioGroup.Label: 라디오 그룹에 대한 정보를 사용자에게 주는 라벨이에요.
  • RadioGroup.Description: 라디오 그룹에 대한 더 많은 정보를 사용자에게 주는 설명이에요.
  • RadioGroup.ErrorMessage: 라디오 그룹의 유효성 검사 오류를 해결하는 방법을 사용자에게 알려주는 오류 메시지예요.

라디오 항목은 다음 요소들로 구성돼요:

  • RadioGroup.Item: 라디오 버튼의 루트 컨테이너예요.
  • RadioGroup.ItemInput: 라디오 버튼 안에 시각적으로 숨겨진 네이티브 html input이에요.
  • RadioGroup.ItemControl: 라디오 버튼을 시각적으로 나타내는 요소예요.
  • RadioGroup.ItemIndicator: 라디오 버튼이 체크된 상태일 때 렌더링되는 시각적 표시자예요.
  • RadioGroup.ItemLabel: 라디오 버튼에 대한 정보를 사용자에게 주는 라벨이에요.
  • RadioGroup.ItemDescription: 라디오 버튼에 대한 더 많은 정보를 사용자에게 주는 설명이에요.
<RadioGroup>
	<RadioGroup.Label />
	<RadioGroup.Item>
		<RadioGroup.ItemInput />
		<RadioGroup.ItemControl>
			<RadioGroup.ItemIndicator />
		</RadioGroup.ItemControl>
		<RadioGroup.ItemLabel />
		<RadioGroup.ItemDescription />
	</RadioGroup.Item>
	<RadioGroup.Description />
	<RadioGroup.ErrorMessage />
</RadioGroup>

Example

Usage

Default value

각 라디오의 value prop에 대응하는 값을 받는 defaultValue prop으로 초기 비제어(uncontrolled) 값을 제공할 수 있어요.

<RadioGroup defaultValue="Orange">
	<RadioGroup.Label>Favorite fruit</RadioGroup.Label>
	<div role="presentation">
		<For each={["Apple", "Orange", "Watermelon"]}>
			{fruit => <RadioGroup.Item value={fruit}>...</RadioGroup.Item>}
		</For>
	</div>
</RadioGroup>

role="presentation"은 Chromium 계열 브라우저의 버그(의미론을 잘못 파싱해 스크린 리더를 깨뜨리는 문제) 때문에 RadioGroup과 RadioGroup.Item 사이의 모든 비-콘텐츠 요소에 필요해요.

Controlled value

각 라디오의 value prop에 대응하는 값을 받는 value prop을 사용해 값을 제어(controlled) 방식으로 만들 수 있어요. 사용자가 라디오를 선택하면 onChange 이벤트가 발생하며 새 값을 받아요.

import { createSignal } from "solid-js";

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

	return (
		<>
			<RadioGroup value={value()} onChange={setValue}>
				<RadioGroup.Label>Favorite fruit</RadioGroup.Label>
				<div role="presentation">
					<For each={["Apple", "Orange", "Watermelon"]}>
						{fruit => <RadioGroup.Item value={fruit}>...</RadioGroup.Item>}
					</For>
				</div>
			</RadioGroup>
			<p>Your favorite fruit is: {value()}.</p>
		</>
	);
}

Description

RadioGroup.Description 컴포넌트를 사용해 라디오 그룹에 추가 도움말 텍스트를 연결할 수 있어요.

<RadioGroup>
	<RadioGroup.Label>Favorite fruit</RadioGroup.Label>
	<div role="presentation">
		<For each={["Apple", "Orange", "Watermelon"]}>
			{fruit => <RadioGroup.Item value={fruit}>...</RadioGroup.Item>}
		</For>
	</div>
	<RadioGroup.Description>Choose the fruit you like the most.</RadioGroup.Description>
</RadioGroup>

Error message

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

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

import { createSignal } from "solid-js";

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

	return (
		<RadioGroup
			value={value()}
			onChange={setValue}
			validationState={value() !== "Apple" ? "invalid" : "valid"}
		>
			<RadioGroup.Label>Favorite fruit</RadioGroup.Label>
			<div role="presentation">
				<For each={["Apple", "Orange", "Watermelon"]}>
					{fruit => <RadioGroup.Item value={fruit}>...</RadioGroup.Item>}
				</For>
			</div>
			<RadioGroup.ErrorMessage>Hmm, I prefer apples.</RadioGroup.ErrorMessage>
		</RadioGroup>
	);
}

HTML forms

라디오 그룹의 name prop을 라디오의 value prop과 함께 사용해 HTML 폼과 통합할 수 있어요.

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

	return (
		<form onSubmit={onSubmit}>
			<RadioGroup name="favorite-fruit">
				<RadioGroup.Label>Favorite fruit</RadioGroup.Label>
				<div role="presentation">
					<For each={["Apple", "Orange", "Watermelon"]}>
						{fruit => <RadioGroup.Item value={fruit}>...</RadioGroup.Item>}
					</For>
				</div>
			</RadioGroup>
			<div>
				<button type="reset">Reset</button>
				<button type="submit">Submit</button>
			</div>
		</form>
	);
}

API Reference

RadioGroup

RadioGroup은 @kobalte/core/radio-group의 Root import와 동일해요(그리고 폐기(deprecated)된 RadioGroup.Root).

Prop Description
value string
The controlled value of the radio button to check.
defaultValue string
The value of the radio button that should be checked when initially rendered. Useful when you do not need to control the state of the radio buttons.
onChange (value: string) => void
Event handler called when the value changes.
orientation 'horizontal' | 'vertical'
The axis the radio group items should align with.
name string
The name of the radio group. Submitted with its owning form as part of a name/value pair.
validationState 'valid' | 'invalid'
Whether the radio group should display its "valid" or "invalid" visual styling.
required boolean
Whether the user must check a radio group item before the owning form can be submitted.
disabled boolean
Whether the radio group is disabled.
readOnly boolean
Whether the radio group items can be selected but not changed by the user.
Data attribute Description
data-valid Present when the radio group is valid according to the validation rules.
data-invalid Present when the radio group is invalid according to the validation rules.
data-required Present when the user must check a radio group item before the owning form can be submitted.
data-disabled Present when the radio group is disabled.
data-readonly Present when the radio group is read only.

RadioGroup.Label, RadioGroup.Description and RadioGroup.ErrorMessage shares the same data-attributes.

RadioGroup.ErrorMessage

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

RadioGroup.Item

Prop Description
value string
The value of the radio button, used when submitting an HTML form. See MDN.
disabled boolean
Whether the radio button is disabled or not.
Data attribute Description
data-valid Present when the parent radio group is valid according to the validation rules.
data-invalid Present when the parent radio group is invalid according to the validation rules.
data-checked Present when the radio is checked.
data-disabled Present when the radio is disabled.

RadioGroup.ItemInput, RadioGroup.ItemControl, RadioGroup.ItemIndicator and RadioGroup.ItemLabel shares the same data-attributes.

RadioGroup.ItemIndicator

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

Rendered elements

Component Default rendered element
RadioGroup div
RadioGroup.Label span
RadioGroup.Description div
RadioGroup.ErrorMessage div
RadioGroup.Item div
RadioGroup.ItemInput input
RadioGroup.ItemControl div
RadioGroup.ItemIndicator div
RadioGroup.ItemLabel label
RadioGroup.ItemDescription div

Accessibility

Keyboard Interactions

Key Description
Tab Moves focus to either the checked radio button or the first radio button in the group.
Space When focus is on an unchecked radio button, checks it.
ArrowDown Moves focus and checks the next radio button in the group.
ArrowRight Moves focus and checks the next radio button in the group.
ArrowUp Moves focus and checks the previous radio button in the group.
ArrowLeft Moves focus and checks the previous radio button in the group.

더 알아보기 (Learn more)