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

토글

원문 보기 위키 갱신

토글 (Toggle)

켜거나 끌 수 있는 두 가지 상태의 버튼을 표시하는 고품질 비스타일(unstyled) React toggle 컴포넌트예요. 좋아요(하트) 버튼처럼 단일 항목을 토글할 때 사용해요.

출처: Base UI Toggle

본문

누름(pressed) 상태와 누르지 않은 상태를 오가는 토글 버튼 컴포넌트예요. 제어(pressed) 또는 비제어(defaultPressed) 방식으로 상태를 다룰 수 있고, render prop으로 상태에 따라 서로 다른 아이콘을 렌더링할 수 있어요.

데모 (Demo)

Tailwind

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

/* index.tsx */
'use client';
import * as React from 'react';
import { Toggle } from '@base-ui/react/toggle';

export default function ExampleToggle() {
  return (
    <Toggle
      aria-label="Favorite"
      className="flex size-8 items-center justify-center border-none rounded-none bg-transparent text-neutral-950 dark:text-white select-none hover:not-data-disabled:bg-neutral-100 dark:hover:not-data-disabled:bg-neutral-800 active:not-data-disabled:bg-neutral-200 dark:active:not-data-disabled:bg-neutral-700 data-pressed:text-neutral-950 dark:data-pressed:text-white focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-neutral-950 dark:focus-visible:outline-white"
      render={(props, state) => {
        if (state.pressed) {
          return (
            <button type="button" {...props}>
              <HeartFilledIcon />
            </button>
          );
        }

        return (
          <button type="button" {...props}>
            <HeartOutlineIcon />
          </button>
        );
      }}
    />
  );
}

function HeartFilledIcon(props: React.ComponentProps<'svg'>) {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 16 16"
      fill="currentColor"
      {...props}
      style={{ display: 'block', ...props.style }}
    >
      <path d="M7.99961 13.8667C7.88761 13.8667 7.77561 13.8315 7.68121 13.7611C7.43321 13.5766 1.59961 9.1963 1.59961 5.8667C1.59961 3.80856 3.27481 2.13336 5.33294 2.13336C6.59054 2.13336 7.49934 2.81176 7.99961 3.3131C8.49988 2.81176 9.40868 2.13336 10.6663 2.13336C12.7244 2.13336 14.3996 3.80803 14.3996 5.8667C14.3996 9.1963 8.56601 13.5766 8.31801 13.7616C8.22361 13.8315 8.11161 13.8667 7.99961 13.8667Z" />
    </svg>
  );
}

function HeartOutlineIcon(props: React.ComponentProps<'svg'>) {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 16 16"
      fill="currentColor"
      {...props}
      style={{ display: 'block', ...props.style }}
    >
      <path
        fillRule="evenodd"
        clipRule="evenodd"
        d="m7.99961 4.8232-.75505-.75666c-.40333-.40419-1.0559-.86651-1.91162-.86651-1.46903 0-2.66666 1.19764-2.66666 2.66667 0 .5412.24648 1.2356.75339 2.04713.49581.79376 1.17682 1.59861 1.89311 2.33647 1.06989 1.1022 2.1604 1.9962 2.68705 2.4102.52751-.4149 1.61735-1.3085 2.68657-2.4101.7163-.73792 1.3973-1.54278 1.8932-2.33656.5069-.81154.7533-1.50594.7533-2.04714 0-1.46947-1.1975-2.66667-2.6666-2.66667-.85574 0-1.50831.46232-1.91164.86651zm-.01387-1.52394c-.5031-.49988-1.40673-1.1659-2.6528-1.1659-2.05813 0-3.73333 1.6752-3.73333 3.73334 0 3.3296 5.8336 7.7099 6.0816 7.8944a.532.532 0 0 0 .3184.1056c.112 0 .224-.0352.3184-.1051.248-.185 6.08159-4.5653 6.08159-7.8949 0-2.05867-1.6752-3.73334-3.7333-3.73334-1.24617 0-2.14985.66611-2.65293 1.166q-.0069.00686-.0137.01367c.00002-.00003-.00002.00002 0 0-.00459-.0046-.00927-.00914-.01393-.01377"
      />
    </svg>
  );
}

CSS Modules

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

/* index.module.css */
.Button {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 2rem;
  height: 2rem;
  padding: 0;
  margin: 0;
  border: none;
  border-radius: 0;
  background-color: transparent;
  color: oklch(14.5% 0 0deg);
  -webkit-user-select: none;
  user-select: none;

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

  @media (hover: hover) {
    &:hover:not([data-disabled]) {
      background-color: oklch(97% 0 0deg);

      @media (prefers-color-scheme: dark) {
        background-color: oklch(26.9% 0 0deg);
      }
    }
  }

  &:active:not([data-disabled]) {
    background-color: oklch(92.2% 0 0deg);

    @media (prefers-color-scheme: dark) {
      background-color: oklch(37.1% 0 0deg);
    }
  }

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

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

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

    @media (prefers-color-scheme: dark) {
      outline-color: white;
    }
  }
}
/* index.tsx */
'use client';
import * as React from 'react';
import { Toggle } from '@base-ui/react/toggle';
import styles from './index.module.css';

export default function ExampleToggle() {
  return (
    <div className={styles.Panel}>
      <Toggle
        aria-label="Favorite"
        className={styles.Button}
        render={(props, state) => {
          if (state.pressed) {
            return (
              <button type="button" {...props}>
                <HeartFilledIcon />
              </button>
            );
          }

          return (
            <button type="button" {...props}>
              <HeartOutlineIcon />
            </button>
          );
        }}
      />
    </div>
  );
}

function HeartFilledIcon(props: React.ComponentProps<'svg'>) {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 16 16"
      fill="currentColor"
      {...props}
      style={{ display: 'block', ...props.style }}
    >
      <path d="M7.99961 13.8667C7.88761 13.8667 7.77561 13.8315 7.68121 13.7611C7.43321 13.5766 1.59961 9.1963 1.59961 5.8667C1.59961 3.80856 3.27481 2.13336 5.33294 2.13336C6.59054 2.13336 7.49934 2.81176 7.99961 3.3131C8.49988 2.81176 9.40868 2.13336 10.6663 2.13336C12.7244 2.13336 14.3996 3.80803 14.3996 5.8667C14.3996 9.1963 8.56601 13.5766 8.31801 13.7616C8.22361 13.8315 8.11161 13.8667 7.99961 13.8667Z" />
    </svg>
  );
}

function HeartOutlineIcon(props: React.ComponentProps<'svg'>) {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 16 16"
      fill="currentColor"
      {...props}
      style={{ display: 'block', ...props.style }}
    >
      <path
        fillRule="evenodd"
        clipRule="evenodd"
        d="m7.99961 4.8232-.75505-.75666c-.40333-.40419-1.0559-.86651-1.91162-.86651-1.46903 0-2.66666 1.19764-2.66666 2.66667 0 .5412.24648 1.2356.75339 2.04713.49581.79376 1.17682 1.59861 1.89311 2.33647 1.06989 1.1022 2.1604 1.9962 2.68705 2.4102.52751-.4149 1.61735-1.3085 2.68657-2.4101.7163-.73792 1.3973-1.54278 1.8932-2.33656.5069-.81154.7533-1.50594.7533-2.04714 0-1.46947-1.1975-2.66667-2.6666-2.66667-.85574 0-1.50831.46232-1.91164.86651zm-.01387-1.52394c-.5031-.49988-1.40673-1.1659-2.6528-1.1659-2.05813 0-3.73333 1.6752-3.73333 3.73334 0 3.3296 5.8336 7.7099 6.0816 7.8944a.532.532 0 0 0 .3184.1056c.112 0 .224-.0352.3184-.1051.248-.185 6.08159-4.5653 6.08159-7.8949 0-2.05867-1.6752-3.73334-3.7333-3.73334-1.24617 0-2.14985.66611-2.65293 1.166q-.0069.00686-.0137.01367c.00002-.00003-.00002.00002 0 0-.00459-.0046-.00927-.00914-.01393-.01377"
      />
    </svg>
  );
}

구조 (Anatomy)

컴포넌트를 임포트하고 단일 파트로 사용해요.

import { Toggle } from '@base-ui/react/toggle';

<Toggle />;

API 레퍼런스

Toggle

켜거나 끌 수 있는 두 가지 상태의 버튼이에요. <button> 요소를 렌더링해요.

Toggle Props:

Prop Type Default Description
value string - 토글을 토글 그룹 안에서 식별하는 고유 문자열. 토글 그룹 안에서 사용될 때 쓰여요.
defaultPressed boolean false 토글 버튼이 현재 눌려 있는지 여부. pressed의 비제어 대응 버전이에요.
pressed boolean - 토글 버튼이 현재 눌려 있는지 여부. defaultPressed의 제어 대응 버전이에요.
onPressedChange ((pressed: boolean, eventDetails: Toggle.ChangeEventDetails) => void) - 눌림(pressed) 상태가 변경될 때 호출되는 콜백.
nativeButton boolean true render prop으로 요소를 대체할 때 네이티브 <button> 요소를 렌더링할지 여부. 렌더링되는 요소가 버튼이 아니면(예를 들어 <div>) false로 설정하세요.
disabled boolean false 컴포넌트가 사용자 상호작용을 무시해야 하는지 여부.
className string \| ((state: Toggle.State) => string \| undefined) - 요소에 적용되는 CSS 클래스, 또는 컴포넌트 상태에 따라 클래스를 반환하는 함수.
style React.CSSProperties \| ((state: Toggle.State) => React.CSSProperties \| undefined) - 요소에 적용되는 스타일, 또는 컴포넌트 상태에 따라 스타일 객체를 반환하는 함수.
render ReactElement \| ((props: HTMLProps, state: Toggle.State) => ReactElement) - 컴포넌트의 HTML 요소를 다른 태그로 대체하거나 다른 컴포넌트와 합성할 수 있게 해줘요. ReactElement 또는 렌더링할 요소를 반환하는 함수를 받아요.

Toggle Data Attributes:

Attribute Type Description
data-pressed - 토글 버튼이 눌렸을 때 존재해요.
data-disabled - 토글 버튼이 비활성화되었을 때 존재해요.

Toggle.Props

Toggle props의 재내보내기예요.

Toggle.State

type ToggleState = {
  /** Whether the toggle is currently pressed. */
  pressed: boolean;
  /** Whether the toggle should ignore user interaction. */
  disabled: boolean;
};

Toggle.ChangeEventReason

type ToggleChangeEventReason = 'none';

Toggle.ChangeEventDetails

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

Canonical Types

Canonical: Alias 매핑 — Canonical의 네임스페이스가 이미 임포트되어 있으면 Canonical을, 아니면 Alias를 사용하세요.

  • Toggle.State: ToggleState
  • Toggle.Props: ToggleProps
  • Toggle.ChangeEventReason: ToggleChangeEventReason
  • Toggle.ChangeEventDetails: ToggleChangeEventDetails

더 알아보기 (Learn more)