Toggle Button (토글 버튼)
토글 버튼은 켜짐(pressed) 또는 꺼짐(not pressed) 두 가지 상태를 가질 수 있는 버튼이에요. 설정이나 필터처럼 ON/OFF가 필요한 동작에 유용하게 사용할 수 있어요.
출처: 문서
본문
Import (불러오기)
import { ToggleButton } from "@kobalte/core/toggle-button";
// or
import { Root } from "@kobalte/core/toggle-button";
// or (deprecated)
import { ToggleButton } from "@kobalte/core";
Features (기능)
- 네이티브 HTML
<button>,<a>및 사용자 지정 요소 타입을 지원해요. - WAI ARIA Button 디자인 패턴을 통해 토글 버튼으로 노출돼요.
- 마우스·터치 이벤트 처리와 눌림 상태 관리를 지원해요.
- Space 및 Enter 키에 대한 키보드 이벤트를 지원해요.
- 제어 방식(controlled) 또는 비제어 방식(uncontrolled)으로 사용할 수 있어요.
Anatomy (구조)
토글 버튼은 다음의 부분들로 이루어져요:
- ToggleButton: 토글 버튼의 루트 컨테이너예요.
<ToggleButton />
Example (예제)
기본 예제를 통해 토글 버튼의 구조와 스타일링 방식을 확인해 보세요. 인터랙티브한 미리보기는 출처 문서에서 직접 확인할 수 있어요.
Usage (사용법)
Default pressed (기본 눌림 상태)
defaultPressed prop을 사용하면 초기의 비제어 값을 지정할 수 있어요.
<ToggleButton defaultPressed>...</ToggleButton>
Controlled pressed (제어 방식 눌림 상태)
pressed prop을 사용하면 눌림 상태를 제어할 수 있어요. 사용자가 버튼을 토글하면 onChange 이벤트가 발생하고 새 값이 전달되답니다.
import { createSignal } from "solid-js";
function ControlledExample() {
const [pressed, setPressed] = createSignal(false);
return (
<>
<ToggleButton pressed={pressed()} onChange={setPressed}>
...
</ToggleButton>
<p>The microphone is {pressed() ? "muted" : "active"}.</p>
</>
);
}
API Reference (API 참조)
ToggleButton
ToggleButton은 @kobalte/core/toggle-button의 Root 임포트(그리고 더 이상 사용되지 않는 ToggleButton.Root)와 동일해요.
ToggleButton은 Button과 추가 prop으로 구성돼요.
| Prop | Description |
|---|---|
| pressed | boolean The controlled pressed state of the toggle button. |
| defaultPressed | boolean The default pressed state when initially rendered. Useful when you do not need to control the pressed state. |
| onChange | (pressed: boolean) => void Event handler called when the pressed state of the toggle button changes. |
| children | JSX.Element | (state: ToggleButtonState) => JSX.Element The children of the toggle button. Can be a JSX.Element or a render prop for having access to the internal state. |
| Render Prop | Description |
|---|---|
| pressed | Accessor<boolean> Whether the toggle button is on (pressed) or off (not pressed). |
| Data attribute | Description |
|---|---|
| data-pressed | Present when the toggle button is on (pressed). |
Rendered elements (렌더링되는 요소)
| Component | Default rendered element |
|---|---|
ToggleButton |
button |
Accessibility (접근성)
Keyboard Interactions (키보드 상호작용)
| Key | Description |
|---|---|
| Space | Activates/deactivates the toggle button. |
| Enter | Activates/deactivates the toggle button. |
더 알아보기 (Learn more)
- Button 컴포넌트 — 토글 버튼의 기반 컴포넌트
- WAI ARIA Button 패턴 — 접근성 가이드라인
- Kobalte 시작하기 — 프로젝트 설정