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

Switch (스위치)

원문 보기 위키 갱신

스위치는 사용자가 켜짐(on) 또는 꺼짐(off) 중 하나의 값을 선택할 수 있게 해주는 컨트롤이에요. 설정 화면에서 자주 볼 수 있는 ON/OFF 토글 형태와 동일하답니다.

출처: 문서

본문

Import (불러오기)

import { Switch } from "@kobalte/core/switch";
// or
import { Root, Input, ... } from "@kobalte/core/switch";
// or (deprecated)
import { Switch } from "@kobalte/core";

Features (기능)

  • WAI ARIA Switch 디자인 패턴을 따릅니다.
  • 사용자 지정 스타일링을 위해 시각적으로 숨겨진 네이티브 HTML <input> 요소로 만들어져요.
  • 폼 reset 이벤트와 동기화돼요.
  • 보조 기술(assistive technology)을 위한 라벨링을 지원해요.
  • ARIA를 통해 input에 연결된 설명(description)과 오류 메시지 도움말 텍스트를 지원해요.
  • 제어 방식(controlled) 또는 비제어 방식(uncontrolled)으로 사용할 수 있어요.

Anatomy (구조)

스위치는 다음의 부분들로 이루어져요:

  • Switch: 스위치의 루트 컨테이너예요.
  • Switch.Input: 스위치에서 시각적으로 숨겨진 네이티브 html input이에요.
  • Switch.Control: 스위치를 시각적으로 나타내는 요소예요.
  • Switch.Thumb: 스위치가 켜졌는지 꺼졌는지를 시각적으로 나타내는 썸(thumb)이에요.
  • Switch.Label: 스위치에 대한 정보를 사용자에게 알려주는 라벨이에요.
  • Switch.Description: 스위치에 대한 더 많은 정보를 사용자에게 알려주는 설명이에요.
  • Switch.ErrorMessage: 스위치의 검증 오류를 어떻게 고치는지에 대한 정보를 사용자에게 알려주는 오류 메시지예요.
<Switch>
	<Switch.Label />
	<Switch.Description />
	<Switch.ErrorMessage />
	<Switch.Input />
	<Switch.Control>
		<Switch.Thumb />
	</Switch.Control>
</Switch>

Example (예제)

기본 예제를 통해 스위치의 구조와 스타일링 방식을 확인해 보세요. 인터랙티브한 미리보기는 출처 문서에서 직접 확인할 수 있어요.

Usage (사용법)

Default checked (기본 체크 상태)

defaultChecked prop을 사용하면 초기의 비제어 값을 지정할 수 있어요.

<Switch defaultChecked>...</Switch>

Controlled checked (제어 방식 체크 상태)

checked prop을 사용하면 체크 상태를 제어할 수 있어요. 사용자가 스위치를 토글하면 onChange 이벤트가 발생하고 새 값이 전달되답니다.

import { createSignal } from "solid-js";

export function ControlledExample() {
	const [checked, setChecked] = createSignal(false);

	return (
		<>
			<Switch checked={checked()} onChange={setChecked}>
				...
			</Switch>
			<p>Airplane mode is {checked() ? "active" : "inactive"}.</p>
		</>
	);
}

Description (설명)

Switch.Description 컴포넌트를 사용하면 스위치에 추가적인 도움말 텍스트를 연결할 수 있어요.

<Switch>
	<Switch.Label>Airplane mode</Switch.Label>
	<Switch.Description>Disable all network connections.</Switch.Description>
	<Switch.Input />
	<Switch.Control>
		<Switch.Thumb />
	</Switch.Control>
</Switch>

Error message (오류 메시지)

Switch.ErrorMessage 컴포넌트를 사용하면 검증 오류를 고칠 수 있도록 도와줄 수 있어요. 보조 기술을 위해 스위치를 의미적으로(invalid) 표시하려면 validationState prop과 함께 사용해야 해요.

기본적으로 validationState prop이 invalid로 설정된 경우에만 렌더링돼요. 오류 메시지를 항상 렌더링하려면 forceMount prop을 사용하세요 (예: 애니메이션 라이브러리와 함께 사용할 때).

import { createSignal } from "solid-js";

function ErrorMessageExample() {
	const [checked, setChecked] = createSignal(false);

	return (
		<Switch
			checked={checked()}
			onChange={setChecked}
			validationState={!checked() ? "invalid" : "valid"}
		>
			<Switch.Label>Airplane mode</Switch.Label>
			<Switch.ErrorMessage>You must enable airplane mode.</Switch.ErrorMessage>
			<Switch.Input />
			<Switch.Control>
				<Switch.Thumb />
			</Switch.Control>
		</Switch>
	);
}

HTML forms

name 와 value prop을 사용하면 HTML 폼과 통합할 수 있어요.

function HTMLFormExample() {
	const onSubmit = (e: SubmitEvent) => {
		// handle form submission.
	};
	return (
		<form onSubmit={onSubmit}>
			<Switch name="airplane-mode" value="on">
				...
			</Switch>
			<div>
				<button type="reset">Reset</button>
				<button type="submit">Submit</button>
			</div>
		</form>
	);
}

API Reference (API 참조)

Switch

Switch은 @kobalte/core/switch의 Root 임포트(그리고 더 이상 사용되지 않는 Switch.Root)와 동일해요.

Prop Description
checked boolean
The controlled checked state of the switch.
defaultChecked boolean
The default checked state when initially rendered. Useful when you do not need to control the checked state.
onChange (checked: boolean) => void
Event handler called when the checked state of the switch changes.
name string
The name of the switch, used when submitting an HTML form. See MDN.
value string
The value of the switch, used when submitting an HTML form. See MDN.
validationState 'valid' | 'invalid'
Whether the switch should display its "valid" or "invalid" visual styling.
required boolean
Whether the user must check the switch before the owning form can be submitted.
disabled boolean
Whether the switch is disabled.
readOnly boolean
Whether the switch can be checked but not changed by the user.
Render Prop Description
checked Accessor<boolean>
Whether the switch is checked or not.
Data attribute Description
data-valid Present when the switch is valid according to the validation rules.
data-invalid Present when the switch is invalid according to the validation rules.
data-required Present when the switch is required.
data-disabled Present when the switch is disabled.
data-readonly Present when the switch is read only.
data-checked Present when the switch is checked.

Switch.Input, Switch.Control, Switch.Thumb, Switch.Label, Switch.Description 및 Switch.ErrorMessage는 동일한 data-attribute를 공유해요.

Switch.ErrorMessage

Prop Description
forceMount boolean
Used to force mounting when more control is needed. Useful when controlling animation with SolidJS animation libraries.

Rendered elements (렌더링되는 요소)

Component Default rendered element
Switch div
Switch.Input input
Switch.Control div
Switch.Thumb div
Switch.Label label
Switch.Description div
Switch.ErrorMessage div

Accessibility (접근성)

Keyboard Interactions (키보드 상호작용)

Key Description
Space Toggles the switch on and off.

더 알아보기 (Learn more)