Switch
Binary toggle control for settings and preferences where users need an immediate on or off action with optional descriptive context.
AccessibleDark Mode3 SizesAnimatedKeyboard Nav
Install
$
npx react-principles add switch01
Theme Preview
Light
Notifications sm
Preview of the sm switch size. (disabled)
Notifications md
Preview of the md switch size. (enabled)
Notifications lg
Preview of the lg switch size. (enabled)
Dark
Notifications sm
Preview of the sm switch size. (disabled)
Notifications md
Preview of the md switch size. (enabled)
Notifications lg
Preview of the lg switch size. (enabled)
02
Live Demo
Size
Enable analytics
Analytics is active (enabled)
03
Code Snippet
src/ui/Switch.tsx
import { Switch } from "@/ui/Switch"; <Switch checked={enabled} onChange={setEnabled} label="Enable analytics" description="Track usage data for product insights." />
04
Copy-Paste (Single File)
Switch.tsx
import { useMemo, useState } from "react"; import { cn } from "@/lib/utils"; export type SwitchSize = "sm" | "md" | "lg"; export interface SwitchProps { checked?: boolean; defaultChecked?: boolean; onChange?: (checked: boolean) => void; disabled?: boolean; size?: SwitchSize; label?: string; description?: string; className?: string; }
05
Props
| Prop | Type | Default | Description |
|---|---|---|---|
checked | boolean | — | Controlled on or off state. |
defaultChecked | boolean | false | Initial state when the switch is uncontrolled. |
onChange | (checked: boolean) => void | — | Called whenever the switch toggles. |
disabled | boolean | false | Prevents interaction and reduces opacity. |
size | "sm" | "md" | "lg" | "md" | Changes the track and thumb dimensions. |
label | string | — | Primary label rendered next to the control. |
description | string | — | Secondary helper text rendered below the label. |
className | string | — | Additional classes applied to the root wrapper. |