Switch (스위치)
Switch는 on/off 두 상태를 오가는 토글 컨트롤이에요. 보통 기능을 켜고 끄거나 설정을 토글할 때 쓰고, 이진 선택에서는 체크박스보다 직관적이고 인터랙티브한 대안이 됩니다. WAI-ARIA 지침을 바탕으로 키보드와 화면 리더까지 잘 지원합니다.
출처: 문서
본문
<script lang="ts">
import { Label, Switch } from "bits-ui";
</script>
<div class="flex items-center space-x-3">
<Switch.Root
id="dnd"
name="hello"
class="focus-visible:ring-foreground focus-visible:ring-offset-background data-[state=checked]:bg-foreground data-[state=unchecked]:bg-dark-10 data-[state=unchecked]:shadow-mini-inset dark:data-[state=checked]:bg-foreground focus-visible:outline-hidden peer inline-flex h-[36px] min-h-[36px] w-[60px] shrink-0 cursor-pointer items-center rounded-full px-[3px] transition-colors focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
>
<Switch.Thumb
class="bg-background data-[state=unchecked]:shadow-mini dark:border-background/30 dark:bg-foreground dark:shadow-popover pointer-events-none block size-[30px] shrink-0 rounded-full transition-transform data-[state=checked]:translate-x-6 data-[state=unchecked]:translate-x-0 dark:border dark:data-[state=unchecked]:border"
/>
</Switch.Root>
<Label.Root for="dnd" class="text-sm font-medium">Do not disturb</Label.Root>
</div>
개요
Switch 컴포넌트는 직관적이고 접근성 좋은 토글 컨트롤을 제공해서, 사용자가 주로 "on"과 "off" 두 상태 사이를 오갈 수 있게 해요. 기능을 켜고 끄거나 설정을 토글하거나 폼에서 불리언 값을 표현할 때 흔히 쓰이죠. 이진 선택을 다룰 때 기존 체크박스보다 더 시각적이고 인터랙티브한 대안이 됩니다.
주요 기능
- 접근성: WAI-ARIA 지침을 바탕으로 만들어져 키보드 탐색과 화면 리더를 지원해요.
- 상태 관리: on/off 상태를 내부적으로 관리하고, 제어(controlled)·비제어(uncontrolled) 사용 방식을 모두 지원해요.
- 스타일링: 데이터 속성으로 상태 간 부드러운 전환과 커스텀 스타일을 적용할 수 있어요.
- HTML 폼: 폼 제출을 위해 숨겨진 input 요소를 렌더링할 수 있어요.
구조 (Architecture)
Switch 컴포넌트는 크게 두 부분으로 나뉘어요:
- Root: 스위치의 상태와 동작을 관리하는 메인 컨테이너 컴포넌트예요.
- Thumb: 스위치에서 움직이며 현재 상태를 나타내는 부분이에요.
구조
코드에서 Switch 컴포넌트가 어떻게 구성되는지 개요를 보여드릴게요:
<script lang="ts">
import { Switch } from "bits-ui";
</script>
<Switch.Root>
<Switch.Thumb />
</Switch.Root>
재사용 가능한 컴포넌트
애플리케이션 전반에서 쓸 수 있는 커스텀 스위치 컴포넌트를 만들 때 Switch 프리미티브를 사용하는 걸 권장해요.
아래 예시에서는 Checkbox와 Label 컴포넌트로 커스텀 스위치 컴포넌트를 만들어 볼게요.
MySwitch.svelte
<script lang="ts">
import { Switch, Label, useId, type WithoutChildrenOrChild } from "bits-ui";
let {
id = useId(),
checked = $bindable(false),
ref = $bindable(null),
labelText,
...restProps
}: WithoutChildrenOrChild<Switch.RootProps> & {
labelText: string;
} = $props();
</script>
<Switch.Root bind:checked bind:ref {id} {...restProps}>
<Switch.Thumb />
</Switch.Root>
<Label.Root for={id}>{labelText}</Label.Root>
그다음에는 이렇게 만든 MySwitch 컴포넌트를 애플리케이션에서 사용할 수 있어요:
<script lang="ts">
import MySwitch from "$lib/components/MySwitch.svelte";
let notifications = $state(true);
</script>
<MySwitch bind:checked={notifications} labelText="Enable notifications" />
checked 상태 다루기
이번 절에서는 컴포넌트의 checked 상태를 어떻게 관리하는지 다뤄요.
양방향 바인딩 (Two-Way Binding)
간단하고 자동적인 상태 동기화를 위해 bind:checked를 사용해요:
<script lang="ts">
import { Switch } from "bits-ui";
let myChecked = $state(true);
</script>
<button onclick={() => (myChecked = false)}> uncheck </button>
<Switch.Root bind:checked={myChecked} />
완전 제어 (Fully Controlled)
상태의 읽기와 쓰기를 완전히 통제하고 싶다면 Function Binding을 사용해요.
<script lang="ts">
import { Switch } from "bits-ui";
let myChecked = $state(false);
function getChecked() {
return myChecked;
}
function setChecked(newChecked: boolean) {
myChecked = newChecked;
}
</script>
<Switch.Root bind:checked={getChecked, setChecked}>
<!-- ... -->
</Switch.Root>
비활성 상태
disabled prop을 true로 설정하면 스위치를 비활성화할 수 있어요.
<Switch.Root disabled>
<!-- ...-->
</Switch.Root>
HTML 폼
Switch.Root에 name prop을 전달하면 스위치 값을 폼으로 제출하기 위한 숨겨진 input 요소가 렌더링돼요.
기본적으로 스위치가 체크된 상태라면 input은 체크박스 기본값인 'on'으로 제출돼요.
<Switch.Root name="dnd">
<!-- ... -->
</Switch.Root>
커스텀 입력 값
다른 값을 제출하고 싶다면 value prop으로 숨겨진 input의 값을 설정하면 돼요.
예를 들어 문자열 값을 제출하려면 이렇게 할 수 있어요:
<Switch.Root name="dnd" value="hello">
<!-- ... -->
<Switch.Thumb />
</Switch.Root>
필수 (Required)
스위치를 필수로 만들고 싶다면 required prop을 사용해요.
<Switch.Root required>
<!-- ... -->
</Switch.Root>
이렇게 하면 숨겨진 input 요소에 required 속성이 적용되어, 폼 제출이 올바르게 강제돼요.
API 참조
Switch.Root
스위치 상태를 설정하고 관리하는 루트 스위치 컴포넌트예요.
| Property | Type | Description | Details |
|---|---|---|---|
checked $bindable |
boolean |
The checked state of the checkbox.Default: false |
|
onCheckedChange |
function - (checked: boolean) => void |
A callback that is fired when the checked state changes.Default: —— undefined |
|
disabled |
boolean |
Whether or not the switch is disabled.Default: false |
|
name |
string |
The name of the hidden input element, used to identify the input in form submissions.Default: —— undefined |
|
required |
boolean |
Whether or not the switch is required to be checked.Default: false |
|
value |
string |
The value of the hidden input element to be used in form submissions when the switch is checked.Default: —— undefined |
|
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 - type SnippetProps = { checked: boolean } |
The children content to render.Default: —— undefined |
|
child |
Snippet - type SnippetProps = { checked: boolean 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-state |
enum - 'checked' | 'unchecked' |
The switch's checked state. | |
data-checked |
'' |
Present when the switch is checked. | |
data-disabled |
'' |
Present when the switch is disabled. | |
data-switch-root |
'' |
Present on the root element. |
Switch.Thumb
스위치의 현재 상태를 알려 주는 스위치의 썸(thumb)이에요.
| Property | Type | Description | Details |
|---|---|---|---|
ref $bindable |
HTMLSpanElement |
The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null |
|
children |
Snippet - type SnippetProps = { checked: boolean } |
The children content to render.Default: —— undefined |
|
child |
Snippet - type SnippetProps = { checked: boolean 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-state |
enum - 'checked' | 'unchecked' |
The switch's checked state. | |
data-checked |
'' |
Present when the switch is checked. | |
data-switch-thumb |
'' |
Present on the thumb element. |
더 알아보기 (Learn more)
Switch는 이진 상태를 다루는 만큼, 같은 토글 계열인 Toggle·Toggle Group과 함께 이해하면 좋아요. checked 상태 제어 방식(양방향 바인딩·함수 바인딩)은 다른 컴포넌트들과 동일하게 흘러가므로, 상태 관리 문서를 함께 보면 패턴이 자연스럽게 익숙해집니다.