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

체크박스(Checkbox)

원문 보기 위키 갱신

사용자가 옵션을 선택하거나 해제할 수 있게 해주고, 부분 선택(indeterminate) 상태까지 지원하는 컴포넌트예요. 동의 절차나 복잡한 폼 상호작용에서 유용하게 쓰여요.

출처: 문서

본문

<script lang="ts">
  import { Checkbox, Label } from "bits-ui";
  import Check from "phosphor-svelte/lib/Check";
  import Minus from "phosphor-svelte/lib/Minus";
</script>
<div class="flex items-center space-x-3">
  <Checkbox.Root
    id="terms"
    aria-labelledby="terms-label"
    class="border-muted bg-foreground data-[state=unchecked]:border-border-input data-[state=unchecked]:bg-background data-[state=unchecked]:hover:border-dark-40 peer inline-flex size-[25px] items-center justify-center rounded-md border transition-all duration-150 ease-in-out active:scale-[0.98]"
    name="hello"
    indeterminate
  >
    {#snippet children({ checked, indeterminate })}
      <div class="text-background inline-flex items-center justify-center">
        {#if indeterminate}
          <Minus class="size-[15px]" weight="bold" />
        {:else if checked}
          <Check class="size-[15px]" weight="bold" />
        {/if}
      </div>
    {/snippet}
  </Checkbox.Root>
  <Label.Root
    id="terms-label"
    for="terms"
    class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
  >
    Accept terms and conditions
  </Label.Root>
</div>

개요(Overview)

Checkbox 컴포넌트는 Svelte 애플리케이션에서 체크박스 입력을 만드는 유연하고 접근 가능한 방법을 제공해요. checked, unchecked, indeterminate의 세 가지 상태를 지원해 복잡한 폼 상호작용과 데이터 표현을 가능하게 해요.

주요 기능(Key Features)

  • 세 가지 상태 지원(Tri-State Support): checked, unchecked, indeterminate 상태를 처리해 폼 설계에 유연성을 줘요.
  • 접근성(Accessibility): WAI-ARIA 지침에 맞춰 만들어져 키보드 내비게이션과 화면 낭독기를 지원해요.
  • 유연한 상태 관리(Flexible State Management): 제어와 비제어 상태를 모두 지원해 체크박스의 체크 상태를 완전히 제어할 수 있어요.

구조(Architecture)

Checkbox 컴포넌트는 다음 부분으로 구성돼요.

  • Root: 체크박스의 상태와 동작을 관리하는 메인 컴포넌트예요.

구조(Structure)

Checkbox 컴포넌트가 코드에서 어떤 구조로 이루어져 있는지 한눈에 보여드릴게요.

<script lang="ts">
  import { Checkbox } from "bits-ui";
</script>
<Checkbox.Root>
  {#snippet children({ checked, indeterminate })}
    {#if indeterminate}
      -
    {:else if checked}
      ✅
    {:else}
      ❌
    {/if}
  {/snippet}
</Checkbox.Root>

재사용 컴포넌트(Reusable Components)

앱 전반에 걸쳐 사용할 커스텀 체크박스 컴포넌트를 만들 때는 Checkbox 기본 요소를 활용하는 걸 권장해요. 아래 예시는 Checkbox와 Label 컴포넌트를 사용해 커스텀 체크박스 컴포넌트를 만드는 모습이에요.

MyCheckbox.svelte

<script lang="ts">
  import {
    Checkbox,
    Label,
    useId,
    type WithoutChildrenOrChild,
  } from "bits-ui";
  let {
    id = useId(),
    checked = $bindable(false),
    ref = $bindable(null),
    labelRef = $bindable(null),
    labelText,
    ...restProps
  }: WithoutChildrenOrChild<Checkbox.RootProps> & {
    labelText: string;
    labelRef?: HTMLLabelElement | null;
  } = $props();
</script>
<Checkbox.Root {id} bind:checked bind:ref {...restProps}>
  {#snippet children({ checked, indeterminate })}
    {#if indeterminate}
      -
    {:else if checked}
      ✅
    {:else}
      ❌
    {/if}
  {/snippet}
</Checkbox.Root>
<Label.Root for={id} bind:ref={labelRef}>
  {labelText}
</Label.Root>

그러면 앱에서 MyCheckbox 컴포넌트를 이렇게 사용할 수 있어요.

+page.svelte

<script lang="ts">
  import MyCheckbox from "$lib/components/MyCheckbox.svelte";
</script>
<MyCheckbox labelText="Enable notifications" />

checked 상태 관리하기

이 절에서는 Checkbox의 checked 상태를 관리하는 방법을 다뤄요.

양방향 바인딩(Two-Way Binding)

bind:checked를 사용하면 상태가 자동으로 동기화되어 아주 간단해요.

<script lang="ts">
  import { Checkbox } from "bits-ui";
  let myChecked = $state(false);
</script>
<button onclick={() => (myChecked = false)}> uncheck </button>
<Checkbox.Root bind:checked={myChecked} />

완전 제어(Fully Controlled)

함수 바인딩(Function Binding)을 사용하면 상태의 읽기와 쓰기를 완전히 제어할 수 있어요.

<script lang="ts">
  import { Checkbox } from "bits-ui";
  let myChecked = $state(false);
  function getChecked() {
    return myChecked;
  }
  function setChecked(newChecked: boolean) {
    myChecked = newChecked;
  }
</script>
<Checkbox.Root bind:checked={getChecked, setChecked}>
  <!-- ... -->
</Checkbox.Root>

indeterminate 상태 관리하기

이 절에서는 Checkbox의 indeterminate 상태를 관리하는 방법을 다뤄요.

양방향 바인딩(Two-Way Binding)

bind:indeterminate를 사용하면 상태가 자동으로 동기화되어 아주 간단해요.

<script lang="ts">
  import MyCheckbox from "$lib/components/MyCheckbox.svelte";
  let myIndeterminate = $state(true);
</script>
<button onclick={() => (myIndeterminate = false)}>
  clear indeterminate
</button>
<MyCheckbox bind:indeterminate={myIndeterminate} />

완전 제어(Fully Controlled)

함수 바인딩(Function Binding)을 사용하면 상태의 읽기와 쓰기를 완전히 제어할 수 있어요.

<script lang="ts">
  import { Checkbox } from "bits-ui";
  let myIndeterminate = $state(true);
  function getIndeterminate() {
    return myIndeterminate;
  }
  function setIndeterminate(newIndeterminate: boolean) {
    myIndeterminate = newIndeterminate;
  }
</script>
<Checkbox.Root bind:indeterminate={getIndeterminate, setIndeterminate}>
  <!-- ... -->
</Checkbox.Root>

비활성 상태(Disabled State)

disabled prop을 true로 설정하면 체크박스를 비활성화할 수 있어요.

<MyCheckbox disabled labelText="Enable notifications" />

HTML 폼(HTML Forms)

name prop을 설정하면 체크박스의 값을 폼과 함께 제출하기 위해 숨겨진(hidden) 체크박스 인풋이 렌더링돼요.

기본적으로 checked prop이 true라면 체크박스는 기본값 'on'으로 제출돼요.

<MyCheckbox name="notifications" labelText="Enable notifications" />

커스텀 입력 값(Custom Input Value)

다른 값을 제출하고 싶다면 value prop으로 숨겨진 인풋의 값을 설정할 수 있어요.

예를 들어 문자열 값을 제출하고 싶다면 이렇게 하면 돼요.

<MyCheckbox
  value="hello"
  name="notifications"
  labelText="Enable notifications"
/>

필수(Required)

체크박스를 필수로 만들고 싶다면 required prop을 사용할 수 있어요.

<Checkbox.Root required>
  <!-- ... -->
</Checkbox.Root>

이렇게 하면 숨겨진 인풋 요소에 required 속성이 적용되어 폼 제출이 올바르게 강제돼요.

체크박스 그룹(Checkbox Groups)

Checkbox.Group 컴포넌트를 사용해 체크박스 그룹을 만들 수 있어요.

<script lang="ts">
  import { Checkbox } from "bits-ui";
</script>
<Checkbox.Group name="notifications">
  <Checkbox.GroupLabel>Notifications</Checkbox.GroupLabel>
  <Checkbox.Root value="marketing" />
  <Checkbox.Root value="promotions" />
  <Checkbox.Root value="news" />
</Checkbox.Group>

코드 펼치기(Expand Code)

<script lang="ts">
  import { Checkbox, Label, useId } from "bits-ui";
  import Check from "phosphor-svelte/lib/Check";
  import Minus from "phosphor-svelte/lib/Minus";
  let myValue = $state<string[]>(["marketing", "news"]);
</script>
<Checkbox.Group
  class="flex flex-col gap-3"
  bind:value={myValue}
  name="notifications"
  onValueChange={console.log}
>
  <Checkbox.GroupLabel class="text-foreground-alt text-sm font-medium">
    Notifications
  </Checkbox.GroupLabel>
  <div class="flex flex-col gap-4">
    {@render MyCheckbox({ label: "Marketing", value: "marketing" })}
    {@render MyCheckbox({ label: "Promotions", value: "promotions" })}
    {@render MyCheckbox({ label: "News", value: "news" })}
    {@render MyCheckbox({ label: "Updates", value: "updates" })}
  </div>
</Checkbox.Group>
{#snippet MyCheckbox({ value, label }: { value: string; label: string })}
  {@const id = useId()}
  <div class="flex items-center">
    <Checkbox.Root
      {id}
      aria-labelledby="{id}-label"
      class="border-muted bg-foreground data-[state=unchecked]:border-border-input data-[state=unchecked]:bg-background data-[state=unchecked]:hover:border-dark-40 peer inline-flex size-[25px] items-center justify-center rounded-md border transition-all duration-150 ease-in-out active:scale-[0.98]"
      name="hello"
      {value}
    >
      {#snippet children({ checked, indeterminate })}
        <div class="text-background inline-flex items-center justify-center">
          {#if indeterminate}
            <Minus class="size-[15px]" weight="bold" />
          {:else if checked}
            <Check class="size-[15px]" weight="bold" />
          {/if}
        </div>
      {/snippet}
    </Checkbox.Root>
    <Label.Root
      id="{id}-label"
      for={id}
      class="pl-3 text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
    >
      {label}
    </Label.Root>
  </div>
{/snippet}

value 상태 관리하기

이 절에서는 Checkbox 그룹의 value 상태를 관리하는 방법을 다뤄요.

양방향 바인딩(Two-Way Binding)

bind:value를 사용하면 상태가 자동으로 동기화되어 아주 간단해요.

<script lang="ts">
  import { Checkbox } from "bits-ui";
  let myValue = $state<string[]>([]);
</script>
<button
  onclick={() => {
    myValue = ["item-1", "item-2"];
  }}
>
  Open Items 1 and 2
</button>
<Checkbox.Group name="myItems" bind:value={myValue}>
  <Checkbox.GroupLabel>Items</Checkbox.GroupLabel>
  <Checkbox.Root value="item-1" />
  <Checkbox.Root value="item-2" />
  <Checkbox.Root value="item-3" />
</Checkbox.Group>

완전 제어(Fully Controlled)

함수 바인딩(Function Binding)을 사용하면 상태의 읽기와 쓰기를 완전히 제어할 수 있어요.

<script lang="ts">
  import { Checkbox } from "bits-ui";
  let myValue = $state<string[]>([]);
  function getValue() {
    return myValue;
  }
  function setValue(newValue: string[]) {
    myValue = newValue;
  }
</script>
<Checkbox.Group bind:value={getValue, setValue}>
  <!-- ... -->
</Checkbox.Group>

HTML 폼(HTML Forms)

그룹 안의 여러 체크박스에 대해 숨겨진 <input /> 요소를 렌더링하려면 Checkbox.Group에 name을 전달해요. 그러면 모든 하위 체크박스가 동일한 name의 숨겨진 인풋을 렌더링해요.

<Checkbox.Group name="notifications">
  <!-- ... -->
</Checkbox.Group>

Checkbox.Group 컴포넌트를 사용하면 그 하위 Checkbox.Root 컴포넌트들은 그룹의 name, required, disabled 같은 속성을 상속받아 사용해요.

API 참조(API Reference)

Checkbox.Root

체크박스의 상태를 토글하는 버튼 컴포넌트예요.

Property Type Description Details
checked $bindable boolean The checkbox button's checked state.Default: false
onCheckedChange function - (checked: boolean) => void A callback that is fired when the checkbox button's checked state changes.Default:  —— undefined
indeterminate $bindable boolean Whether the checkbox is an indeterminate state or not.Default: false
onIndeterminateChange function - (indeterminate: boolean) => void A callback that is fired when the indeterminate state changes.Default:  —— undefined
disabled boolean Whether or not the checkbox button is disabled. This prevents the user from interacting with it.Default: false
required boolean Whether or not the checkbox is required.Default: false
name string The name of the checkbox. If provided a hidden input will be render to use for form submission. If not provided, the hidden input will not be rendered.Default:  —— undefined
form string The id of a form element the hidden input will be attached.Default:  —— undefined
value string The value of the checkbox. This is what is submitted with the form when the checkbox is checked.Default:  —— undefined
readonly boolean Whether or not the checkbox is read only. If true, the checkbox will be focusable by the user, but will not be able to be checked/unchecked.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 - type ChildrenSnippetProps = { checked: boolean; indeterminate: boolean; }; The children content to render.Default:  —— undefined
child Snippet - type ChildSnippetProps = { props: Record<string, unknown>; checked: boolean; indeterminate: boolean; }; 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' | 'indeterminate' The checkbox's state of checked, unchecked, or indeterminate.
data-disabled '' Present when the checkbox is disabled.
data-readonly '' Present when the checkbox is read only.
data-checkbox-root '' Present on the root element.

Checkbox.Group

value 상태를 하위 체크박스들과 동기화하는 그룹이에요.

Property Type Description Details
value $bindable string[] The value of the group. This is an array of the values of the checked checkboxes within the group.Default: []
onValueChange function - (value: string[]) => void A callback that is fired when the checkbox group's value state changes.Default:  —— undefined
disabled boolean Whether or not the checkbox group is disabled. If true, all checkboxes within the group will be disabled. To disable a specific checkbox in the group, pass the disabled prop to the checkbox.Default: false
required boolean Whether or not the checkbox group is required for form submission.Default: false
name string The name of the checkbox group. If provided a hidden input will be rendered to use for form submission.Default:  —— undefined
readonly boolean Whether or not the checkbox group is read only. If true, the group will be focusable by the user, but the checkboxes will not be able to be checked/unchecked.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-disabled '' Present when the checkbox group is disabled.
data-checkbox-group '' Present on the group element.
data-readonly '' Present when the checkbox group is read only.

Checkbox.GroupLabel

체크박스 그룹의 접근 가능한 라벨이에요.

Property Type Description Details
ref $bindable HTMLLabelElement 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 checkbox group is disabled.
data-checkbox-group-label '' Present on the label element.

더 알아보기 (Learn more)

여러 항목 중 하나만 골라야 한다면 라디오 그룹(Radio Group) 컴포넌트를, 메뉴 안에서 체크박스처럼 항목을 선택하고 싶다면 컨텍스트 메뉴(Context Menu)를 살펴보세요. 폼 라벨은 Label 컴포넌트로 연결하는 게 좋아요.