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

Checkbox

원문 보기 위키 갱신

쉽게 커스터마이즈할 수 있는 품질 높은 비스타일(unstyled) React 체크박스 컴포넌트예요.

출처: Base UI Checkbox

본문

품질이 높고 비스타일이며 커스터마이즈하기 쉬운 React 체크박스 컴포넌트예요.

데모 (Demo)

Tailwind

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

/* index.tsx */
import * as React from 'react';
import { Checkbox } from '@base-ui/react/checkbox';

export default function ExampleCheckbox() {
  return (
    <label className="flex items-center gap-2 text-sm font-normal text-neutral-950 dark:text-white">
      <Checkbox.Root
        defaultChecked
        className="flex size-4 shrink-0 items-center justify-center border rounded-none 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"
      >
        <Checkbox.Indicator className="flex data-unchecked:hidden">
          <CheckIcon />
        </Checkbox.Indicator>
      </Checkbox.Root>
      Enable notifications
    </label>
  );
}

function CheckIcon(props: React.ComponentProps<'svg'>) {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      {...props}
      style={{ display: 'block', ...props.style }}
    >
      <path d="m2.5 8.5 4 4 7-9" />
    </svg>
  );
}

CSS Modules

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

/* index.module.css */
.Label {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.875rem;
  line-height: 1.25rem;
  font-weight: 400;
  color: oklch(14.5% 0 0deg);

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

.Checkbox {
  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: 0;
  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],
  &[data-indeterminate] {
    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;

  &[data-unchecked] {
    display: none;
  }
}
/* index.tsx */
import * as React from 'react';
import { Checkbox } from '@base-ui/react/checkbox';
import styles from './index.module.css';

export default function ExampleCheckbox() {
  return (
    <label className={styles.Label}>
      <Checkbox.Root defaultChecked className={styles.Checkbox}>
        <Checkbox.Indicator className={styles.Indicator}>
          <CheckIcon />
        </Checkbox.Indicator>
      </Checkbox.Root>
      Enable notifications
    </label>
  );
}

function CheckIcon(props: React.ComponentProps<'svg'>) {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      {...props}
      style={{ display: 'block', ...props.style }}
    >
      <path d="m2.5 8.5 4 4 7-9" />
    </svg>
  );
}

사용 가이드라인 (Usage guidelines)

구조 (Anatomy)

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

import { Checkbox } from '@base-ui/react/checkbox';

<Checkbox.Root>
  <Checkbox.Indicator />
</Checkbox.Root>;

예시 (Examples)

체크박스에 라벨 지정하기

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

// @highlight
<label>
  <Checkbox.Root />
  Accept terms and conditions
  {/* @highlight */}
</label>

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

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

<div>
  <label htmlFor="notifications-checkbox">Enable notifications</label>
  {/* @highlight-text "nativeButton" "render={<button />}" */}
  <Checkbox.Root id="notifications-checkbox" nativeButton render={<button />}>
    <Checkbox.Indicator />
  </Checkbox.Root>
</div>

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

<Checkbox.Root
  nativeButton
  // @highlight-start
  render={(buttonProps) => (
    <label>
      <button {...buttonProps} />
      Enable notifications
    </label>
  )}
  {/* @highlight-end */}
/>

폼 통합 (Form integration)

라벨 연결과 폼 통합을 처리하려면 Field를 사용해요:

<Form>
  {/* @highlight */}
  <Field.Root name="stayLoggedIn">
    <Field.Label>
      <Checkbox.Root />
      Stay logged in for 7 days
    </Field.Label>
  </Field.Root>
</Form>

API 레퍼런스

Root

체크박스 자체를 나타내요. <span> 요소와 그 옆에 숨겨진 <input>을 렌더링해요.

Root Props:

Prop Type Default Description
name string undefined 폼이 제출될 때 필드를 식별해요.
defaultChecked boolean false 체크박스가 처음에 체크되어 있는지 여부예요. 제어형 체크박스를 렌더링하려면 대신 checked prop을 사용해요.
checked boolean undefined 체크박스가 현재 체크되어 있는지 여부예요. 비제어형 체크박스를 렌더링하려면 대신 defaultChecked prop을 사용해요.
onCheckedChange ((checked: boolean, eventDetails: Checkbox.Root.ChangeEventDetails) => void) - 체크박스가 체크되거나 체크 해제될 때 호출되는 이벤트 핸들러예요.
indeterminate boolean false 체크박스가 혼합 상태(체크도 체크 해제도 아닌)인지 여부예요.
value string - 체크박스의 값이에요. Checkbox Group 내에서 식별하며, 생략하면 name으로 대체돼요. 폼을 제출할 때 체크된 박스는 value를 제출하고, value가 없으면 네이티브의 "on"을 제출해요.
form string - 숨겨진 input을 소유하는 폼을 식별해요. 체크박스가 폼 바깥에 렌더링될 때 유용해요.
nativeButton boolean false render prop을 통해 요소를 대체할 때 네이티브 <button> 요소를 렌더링할지 여부예요. 렌더링되는 요소가 네이티브 버튼이면 true로 설정해요.
parent boolean false 체크박스가 하위 체크박스 그룹을 제어하는지 여부예요. Checkbox Group에서 사용해야 해요.
uncheckedValue string - 체크박스가 체크되지 않았을 때 폼과 함께 제출되는 값이에요. 기본적으로 체크되지 않은 체크박스는 네이티브 체크박스 동작과 일치하게 어떤 값도 제출하지 않아요.
disabled boolean false 컴포넌트가 사용자 상호작용을 무시할지 여부예요.
readOnly boolean false 사용자가 체크박스를 체크하거나 체크 해제할 수 없어야 하는지 여부예요.
required boolean false 사용자가 폼을 제출하기 전에 체크박스를 체크해야 하는지 여부예요.
inputRef React.Ref<HTMLInputElement> - 숨겨진 <input> 요소에 접근하는 ref예요.
id string - input 요소의 id예요.
className string | ((state: Checkbox.Root.State) => string | undefined) - 요소에 적용되는 CSS 클래스이거나, 컴포넌트 상태에 따라 클래스를 반환하는 함수예요.
style React.CSSProperties | ((state: Checkbox.Root.State) => React.CSSProperties | undefined) - 요소에 적용되는 스타일이거나, 컴포넌트 상태에 따라 스타일 객체를 반환하는 함수예요.
render ReactElement | ((props: HTMLProps, state: Checkbox.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로 감싸져 있을 때).
data-indeterminate - 체크박스가 혼합 상태일 때 나타나요.

Root.Props

Root props의 재수출이에요.

Root.State

type CheckboxRootState = {
  /** Whether the checkbox is currently ticked. */
  checked: boolean;
  /** Whether the component should ignore user interaction. */
  disabled: boolean;
  /** Whether the user should be unable to tick or untick the checkbox. */
  readOnly: boolean;
  /** Whether the user must tick the checkbox before submitting a form. */
  required: boolean;
  /** Whether the checkbox is in a mixed state: neither ticked, nor unticked. */
  indeterminate: 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;
};

Root.ChangeEventReason

type CheckboxRootChangeEventReason = 'none';

Root.ChangeEventDetails

type CheckboxRootChangeEventDetails = {
  /** 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;
};

Indicator

체크박스가 체크되었는지 나타내요. <span> 요소를 렌더링해요.

Indicator Props:

Prop Type Default Description
className string | ((state: Checkbox.Indicator.State) => string | undefined) - 요소에 적용되는 CSS 클래스이거나, 컴포넌트 상태에 따라 클래스를 반환하는 함수예요.
style React.CSSProperties | ((state: Checkbox.Indicator.State) => React.CSSProperties | undefined) - 요소에 적용되는 스타일이거나, 컴포넌트 상태에 따라 스타일 객체를 반환하는 함수예요.
keepMounted boolean false 체크박스가 체크되지 않았을 때 요소를 DOM에 유지할지 여부예요.
render ReactElement | ((props: HTMLProps, state: Checkbox.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-indeterminate - 체크박스가 혼합 상태일 때 나타나요.
data-starting-style - 체크박스 인디케이터가 들어오는 애니메이션을 시작할 때 나타나요.
data-ending-style - 체크박스 인디케이터가 나가는 애니메이션 중일 때 나타나요.

Indicator.Props

Indicator props의 재수출이에요.

Indicator.State

type CheckboxIndicatorState = {
  /** The transition status of the component. */
  transitionStatus: TransitionStatus;
  /** Whether the checkbox is currently ticked. */
  checked: boolean;
  /** Whether the component should ignore user interaction. */
  disabled: boolean;
  /** Whether the user should be unable to tick or untick the checkbox. */
  readOnly: boolean;
  /** Whether the user must tick the checkbox before submitting a form. */
  required: boolean;
  /** Whether the checkbox is in a mixed state: neither ticked, nor unticked. */
  indeterminate: 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;
};

Export Groups

  • Checkbox.Root: Checkbox.Root, Checkbox.Root.State, Checkbox.Root.Props, Checkbox.Root.ChangeEventReason, Checkbox.Root.ChangeEventDetails
  • Checkbox.Indicator: Checkbox.Indicator, Checkbox.Indicator.State, Checkbox.Indicator.Props
  • Default: CheckboxRootState, CheckboxRootProps, CheckboxRootChangeEventReason, CheckboxRootChangeEventDetails, CheckboxIndicatorState, CheckboxIndicatorProps

Canonical Types

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

더 알아보기 (Learn more)