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

Switch

원문 보기 위키 갱신

설정이 켜져 있는지 꺼져 있는지 나타내는 품질 높은 비스타일(unstyled) React 스위치 컴포넌트예요.

출처: Base UI Switch

본문

설정이 켜져 있는지 꺼져 있는지 나타내는 품질이 높고 비스타일인 React 스위치 컴포넌트예요.

데모 (Demo)

Tailwind

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

/* index.tsx */
import { Switch } from '@base-ui/react/switch';

export default function ExampleSwitch() {
  return (
    <label className="flex items-center gap-2 text-sm font-normal text-neutral-950 dark:text-white">
      <Switch.Root
        defaultChecked
        className="flex h-5 w-9 shrink-0 border border-neutral-950 bg-white p-0.5 transition-colors duration-150 ease-[ease] dark:border-white dark:bg-neutral-950 data-checked:bg-neutral-950 dark:data-checked:bg-white focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-950 dark:focus-visible:outline-white"
      >
        <Switch.Thumb className="size-3.5 bg-neutral-950 transition-[translate,background-color] duration-150 ease-[ease] data-checked:translate-x-4 data-checked:bg-white dark:bg-white dark:data-checked:bg-neutral-950" />
      </Switch.Root>
      Notifications
    </label>
  );
}

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;
  }
}

.Switch {
  box-sizing: border-box;
  display: flex;
  flex-shrink: 0;
  border: 1px solid oklch(14.5% 0 0deg);
  padding: 0.125rem;
  width: 2.25rem;
  height: 1.25rem;
  background-color: white;
  transition: background-color 150ms ease;

  @media (prefers-color-scheme: dark) {
    border: 1px solid white;
    background-color: oklch(14.5% 0 0deg);
  }

  &[data-checked] {
    background-color: oklch(14.5% 0 0deg);

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

  &:focus-visible {
    outline: 2px solid oklch(14.5% 0 0deg);
    outline-offset: 2px;

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

.Thumb {
  width: 0.875rem;
  height: 0.875rem;
  background-color: oklch(14.5% 0 0deg);
  transition:
    translate 150ms ease,
    background-color 150ms ease;

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

  &[data-checked] {
    translate: 1rem 0;
    background-color: white;

    @media (prefers-color-scheme: dark) {
      background-color: oklch(14.5% 0 0deg);
    }
  }
}
/* index.tsx */
import { Switch } from '@base-ui/react/switch';
import styles from './index.module.css';

export default function ExampleSwitch() {
  return (
    <label className={styles.Label}>
      <Switch.Root defaultChecked className={styles.Switch}>
        <Switch.Thumb className={styles.Thumb} />
      </Switch.Root>
      Notifications
    </label>
  );
}

사용 가이드라인 (Usage guidelines)

구조 (Anatomy)

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

import { Switch } from '@base-ui/react/switch';

<Switch.Root>
  <Switch.Thumb />
</Switch.Root>;

예시 (Examples)

스위치에 라벨 지정하기

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

// @highlight
<label>
  <Switch.Root />
  Notifications
  {/* @highlight */}
</label>

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

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

<div>
  <label htmlFor="notifications-switch">Notifications</label>
  {/* @highlight-text "nativeButton" "render={<button />}" */}
  <Switch.Root id="notifications-switch" nativeButton render={<button />}>
    <Switch.Thumb />
  </Switch.Root>
</div>

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

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

폼 통합 (Form integration)

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

<Form>
  {/* @highlight */}
  <Field.Root name="notifications">
    <Field.Label>
      <Switch.Root />
      Notifications
    </Field.Label>
  </Field.Root>
</Form>

API 레퍼런스

Root

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

Root Props:

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

Root.Props

Root props의 재수출이에요.

Root.State

type SwitchRootState = {
  /** Whether the switch is currently active. */
  checked: boolean;
  /** Whether the component should ignore user interaction. */
  disabled: boolean;
  /** Whether the user should be unable to activate or deactivate the switch. */
  readOnly: boolean;
  /** Whether the user must activate the switch before submitting a form. */
  required: 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 SwitchRootChangeEventReason = 'none';

Root.ChangeEventDetails

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

Thumb

스위치가 켜져 있는지 꺼져 있는지 나타내는 움직이는 부분이에요. <span>을 렌더링해요.

Thumb Props:

Prop Type Default Description
className string | ((state: Switch.Thumb.State) => string | undefined) - 요소에 적용되는 CSS 클래스이거나, 컴포넌트 상태에 따라 클래스를 반환하는 함수예요.
style React.CSSProperties | ((state: Switch.Thumb.State) => React.CSSProperties | undefined) - 요소에 적용되는 스타일이거나, 컴포넌트 상태에 따라 스타일 객체를 반환하는 함수예요.
render ReactElement | ((props: HTMLProps, state: Switch.Thumb.State) => ReactElement) - 컴포넌트의 HTML 요소를 다른 태그로 바꾸거나 다른 컴포넌트와 합성할 수 있게 해줘요. 렌더링할 요소를 반환하는 ReactElement나 함수를 받아요.

Thumb 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로 감싸져 있을 때).

Thumb.Props

Thumb props의 재수출이에요.

Thumb.State

type SwitchThumbState = {
  /** Whether the switch is currently active. */
  checked: boolean;
  /** Whether the component should ignore user interaction. */
  disabled: boolean;
  /** Whether the user should be unable to activate or deactivate the switch. */
  readOnly: boolean;
  /** Whether the user must activate the switch before submitting a form. */
  required: 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

  • Switch.Root: Switch.Root, Switch.Root.State, Switch.Root.Props, Switch.Root.ChangeEventReason, Switch.Root.ChangeEventDetails
  • Switch.Thumb: Switch.Thumb, Switch.Thumb.Props, Switch.Thumb.State
  • Default: SwitchRootState, SwitchRootProps, SwitchRootChangeEventReason, SwitchRootChangeEventDetails, SwitchThumbProps, SwitchThumbState

Canonical Types

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

  • Switch.Root.State: SwitchRootState
  • Switch.Root.Props: SwitchRootProps
  • Switch.Root.ChangeEventReason: SwitchRootChangeEventReason
  • Switch.Root.ChangeEventDetails: SwitchRootChangeEventDetails
  • Switch.Thumb.Props: SwitchThumbProps
  • Switch.Thumb.State: SwitchThumbState

더 알아보기 (Learn more)