Radio Group 문서
Radio Group은 여러 개의 라디오 항목을 하나의 name 아래 묶어 폼 제출까지 처리해 주는 컴포넌트예요. 여러 선택지 중 하나만 고르는 상황에서 기본 라디오 버튼을 다루기 쉽게 만들어 줘요.
출처: 문서
본문
아래 예시는 RadioGroup.Root 안에 항목들을 나열하고, 각 항목을 RadioGroup.Item과 함께 Label로 표시한 모습이에요. 선택된 항목은 data-[state=checked] 스타일로 구분돼요.
<script lang="ts">
import { Label, RadioGroup } from "bits-ui";
</script>
<RadioGroup.Root class="flex flex-col gap-4 text-sm font-medium">
<div
class="text-foreground group flex select-none items-center transition-all"
>
<RadioGroup.Item
id="amazing"
value="amazing"
class="border-border-input bg-background hover:border-dark-40 data-[state=checked]:border-foreground data-[state=checked]:border-6 size-5 shrink-0 cursor-default rounded-full border transition-all duration-100 ease-in-out"
/>
<Label.Root for="amazing" class="pl-3">Amazing</Label.Root>
</div>
<div
class="text-foreground group flex select-none items-center transition-all"
>
<RadioGroup.Item
id="average"
value="average"
class="border-border-input bg-background hover:border-dark-40 data-[state=checked]:border-foreground data-[state=checked]:border-6 size-5 shrink-0 cursor-default rounded-full border transition-all duration-100 ease-in-out"
/>
<Label.Root for="average" class="pl-3">Average</Label.Root>
</div>
<div
class="text-foreground group flex select-none items-center transition-all"
>
<RadioGroup.Item
id="terrible"
value="terrible"
class="border-border-input bg-background hover:border-dark-40 data-[state=checked]:border-foreground data-[state=checked]:border-6 size-5 shrink-0 cursor-default rounded-full border transition-all duration-100 ease-in-out"
/>
<Label.Root for="terrible" class="pl-3">Terrible</Label.Root>
</div>
</RadioGroup.Root>
구조 (Structure)
Radio Group의 기본 구조는 RadioGroup.Root가 그룹을 감싸고, 그 안에 RadioGroup.Item을 배치하는 방식이에요. 항목의 선택 여부 확인은 children snippet이 받는 checked 값으로 판단해요.
<script lang="ts">
import { RadioGroup } from "bits-ui";
</script>
<RadioGroup.Root>
<RadioGroup.Item>
{#snippet children({ checked })}
{#if checked}
✅
{/if}
{/snippet}
</RadioGroup.Item>
</RadioGroup.Root>
재사용 컴포넌트 (Reusable Components)
RadioGroup 프리미티브로 애플리케이션 곳곳에서 쓸 수 있는 나만의 컴포넌트를 만드는 걸 권장해요.
아래 예시는 항목 배열을 받아 각 항목마다 Label을 함께 렌더링하는 MyRadioGroup 컴포넌트를 만든 모습이에요.
MyRadioGroup.svelte
<script lang="ts">
import {
RadioGroup,
Label,
type WithoutChildrenOrChild,
useId,
} from "bits-ui";
type Item = {
value: string;
label: string;
disabled?: boolean;
};
type Props = WithoutChildrenOrChild<RadioGroup.RootProps> & {
items: Item[];
};
let {
value = $bindable(""),
ref = $bindable(null),
items,
...restProps
}: Props = $props();
</script>
<RadioGroup.Root bind:value bind:ref {...restProps}>
{#each items as item}
{@const id = useId()}
<div>
<RadioGroup.Item {id} value={item.value} disabled={item.disabled}>
{#snippet children({ checked })}
{#if checked}
✅
{/if}
{/snippet}
</RadioGroup.Item>
<Label.Root for={id}>{item.label}</Label.Root>
</div>
{/each}
</RadioGroup.Root>
그리고 만든 MyRadioGroup 컴포넌트는 애플리케이션에서 이렇게 사용하면 돼요.
+page.svelte
<script lang="ts">
import MyRadioGroup from "$lib/components/MyRadioGroup.svelte";
const myItems = [
{ value: "apple", label: "Apple" },
{ value: "banana", label: "Banana" },
{ value: "coconut", label: "Coconut", disabled: true },
];
</script>
<MyRadioGroup items={myItems} name="favoriteFruit" />
값 상태 다루기 (Managing Value State)
이번 절에서는 컴포넌트의 value 상태를 어떻게 다루는지 설명할게요.
양방향 바인딩 (Two-Way Binding)
간단하고 자동으로 상태를 동기화하고 싶다면 bind:value를 사용해요.
<script lang="ts">
import { RadioGroup } from "bits-ui";
let myValue = $state("");
</script>
<button onclick={() => (myValue = "A")}> Select A </button>
<RadioGroup.Root bind:value={myValue}>
<!-- ... -->
</RadioGroup.Root>
완전 제어 (Fully Controlled)
상태의 읽기와 쓰기를 모두 직접 제어하고 싶다면 Function Binding을 사용해요.
<script lang="ts">
import { RadioGroup } from "bits-ui";
let myValue = $state("");
function getValue() {
return myValue;
}
function setValue(newValue: string) {
myValue = newValue;
}
</script>
<RadioGroup.Root bind:value={getValue, setValue}>
<!-- ... -->
</RadioGroup.Root>
HTML 폼 (HTML Forms)
RadioGroup.Root 컴포넌트에 name prop을 설정하면, 라디오 그룹의 값을 폼에 제출하기 위한 숨겨진 입력 요소가 렌더링돼요.
<RadioGroup.Root name="favoriteFruit">
<!-- ... -->
</RadioGroup.Root>
필수 (Required)
숨겨진 입력 요소를 required로 만들려면 RadioGroup.Root 컴포넌트에 required prop을 설정하면 돼요.
<RadioGroup.Root required>
<!-- ... -->
</RadioGroup.Root>
항목 비활성화 (Disabling Items)
라디오 그룹의 항목을 비활성화하려면 disabled prop을 true로 설정하면 돼요.
<RadioGroup.Item value="apple" disabled>Apple</RadioGroup.Item>
방향 (Orientation)
orientation prop은 라디오 그룹의 방향을 정하는 데 사용돼요. 이 값에 따라 키보드 탐색 방식이 달라져요.
orientation이 'vertical'이면 ArrowUp과 ArrowDown 키로 항목을 탐색해요. 'horizontal'이면 ArrowLeft와 ArrowRight 키로 탐색해요.
<RadioGroup.Root orientation="vertical">
<!-- ... -->
</RadioGroup.Root>
<RadioGroup.Root orientation="horizontal">
<!-- ... -->
</RadioGroup.Root>
예시 (Examples)
읽기 전용 (Readonly)
라디오 그룹이 읽기 전용이면 사용자가 항목에 포커스하고 탐색할 수는 있지만 선택을 바꿀 수는 없어요. 보여 주기는 해야 하지만 수정할 수는 없어야 하는 정보를 표시할 때 유용해요.
코드 펼치기 (Expand Code)
<script lang="ts">
import { Label, RadioGroup } from "bits-ui";
</script>
<RadioGroup.Root
value="average"
readonly
class="flex flex-col gap-4 text-sm font-medium opacity-75"
>
<div
class="text-foreground group flex select-none items-center transition-all"
>
<RadioGroup.Item
id="readonly-amazing"
value="amazing"
class="border-border-input bg-background hover:border-dark-40 data-[state=checked]:border-foreground data-[state=checked]:border-6 data-readonly:pointer-events-none size-5 shrink-0 cursor-default rounded-full border transition-all duration-100 ease-in-out"
/>
<Label.Root for="readonly-amazing" class="pl-3">Amazing</Label.Root>
</div>
<div
class="text-foreground group flex select-none items-center transition-all"
>
<RadioGroup.Item
id="readonly-average"
value="average"
class="border-border-input bg-background hover:border-dark-40 data-[state=checked]:border-foreground data-[state=checked]:border-6 data-readonly:pointer-events-none size-5 shrink-0 cursor-default rounded-full border transition-all duration-100 ease-in-out"
/>
<Label.Root for="readonly-average" class="pl-3">Average</Label.Root>
</div>
<div
class="text-foreground group flex select-none items-center transition-all"
>
<RadioGroup.Item
id="readonly-terrible"
value="terrible"
class="border-border-input bg-background hover:border-dark-40 data-[state=checked]:border-foreground data-[state=checked]:border-6 data-readonly:pointer-events-none size-5 shrink-0 cursor-default rounded-full border transition-all duration-100 ease-in-out"
/>
<Label.Root for="readonly-terrible" class="pl-3">Terrible</Label.Root>
</div>
</RadioGroup.Root>
<RadioGroup.Root readonly>
<!-- ... -->
</RadioGroup.Root>
비활성화 (Disabled)
라디오 그룹이 비활성화되면 사용자가 전혀 상호작용할 수 없어요. 그룹 전체가 포커스도 불가능하고 상호작용도 불가능해져요.
코드 펼치기 (Expand Code)
<script lang="ts">
import { Label, RadioGroup } from "bits-ui";
</script>
<RadioGroup.Root
value="average"
disabled
class="flex flex-col gap-4 text-sm font-medium opacity-50"
>
<div
class="text-foreground group flex select-none items-center transition-all"
>
<RadioGroup.Item
id="disabled-amazing"
value="amazing"
class="border-border-input bg-background hover:border-dark-40 data-[state=checked]:border-foreground data-[state=checked]:border-6 data-disabled:pointer-events-none size-5 shrink-0 cursor-default rounded-full border transition-all duration-100 ease-in-out"
/>
<Label.Root for="disabled-amazing" class="pl-3">Amazing</Label.Root>
</div>
<div
class="text-foreground group flex select-none items-center transition-all"
>
<RadioGroup.Item
id="disabled-average"
value="average"
class="border-border-input bg-background hover:border-dark-40 data-[state=checked]:border-foreground data-[state=checked]:border-6 data-disabled:pointer-events-none size-5 shrink-0 cursor-default rounded-full border transition-all duration-100 ease-in-out"
/>
<Label.Root for="disabled-average" class="pl-3">Average</Label.Root>
</div>
<div
class="text-foreground group flex select-none items-center transition-all"
>
<RadioGroup.Item
id="disabled-terrible"
value="terrible"
class="border-border-input bg-background hover:border-dark-40 data-[state=checked]:border-foreground data-[state=checked]:border-6 data-disabled:pointer-events-none size-5 shrink-0 cursor-default rounded-full border transition-all duration-100 ease-in-out"
/>
<Label.Root for="disabled-terrible" class="pl-3">Terrible</Label.Root>
</div>
</RadioGroup.Root>
<RadioGroup.Root disabled>
<!-- ... -->
</RadioGroup.Root>
API Reference
RadioGroup.Root
The radio group component used to group radio items under a common name for form submission.
| Property | Type | Description | Details |
|---|---|---|---|
value $bindable |
string |
The value of the currently selected radio item. You can bind to this value to control the radio group's value from outside the component.Default: —— undefined |
|
onValueChange |
function - (value: string) => void |
A callback that is fired when the radio 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 radio group used in form submission. If provided, a hidden input element will be rendered to submit the value of the radio group.Default: —— undefined |
|
loop |
boolean |
Whether or not the radio group should loop through the items when navigating with the arrow keys.Default: false |
|
orientation |
enum - 'vertical' | 'horizontal' |
The orientation of the radio group. This will determine how keyboard navigation will work within the component.Default: 'vertical' |
|
readonly |
boolean |
Whether or not the radio group is readonly. When readonly, users can focus and navigate through items but cannot change the value.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 |
The children content to render.Default: —— undefined |
|
child |
Snippet - type SnippetProps = { 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 radio group. | |
data-disabled |
'' |
Present when the radio group is disabled. | |
data-readonly |
'' |
Present when the radio group is readonly. | |
data-radio-group-root |
'' |
Present on the root element. |
RadioGroup.Item
An radio item, which must be a child of the RadioGroup.Root component.
| Property | Type | Description | Details |
|---|---|---|---|
value required |
string |
The value of the radio item. This should be unique for each radio item in the group.Default: —— undefined |
|
disabled |
boolean |
Whether the radio item is disabled.Default: false |
|
ref $bindable |
HTMLButtonElement |
The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null |
|
children |
Snippet |
The children content to render.Default: —— undefined |
|
child |
Snippet - type SnippetProps = { 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 radio item is disabled. | |
data-readonly |
'' |
Present when the radio group is readonly. | |
data-value |
'' |
The value of the radio item. | |
data-state |
enum - 'checked' | 'unchecked' |
The radio item's checked state. | |
data-orientation |
'' |
The orientation of the parent radio group. | |
data-radio-group-item |
'' |
Present on the radio item element. |
더 알아보기 (Learn more)
Radio Group은 여러 항목 중 하나만 고를 때 사용하고, orientation과 readonly, disabled로 탐색과 상호작용을 조절해요. 비슷하게 여러 항목을 묶어 다루는 Select나 Toggle Group을 함께 살펴보면, 선택형 UI를 상황에 맞게 골라 쓸 수 있어요.