import { Switch, SwitchLabel } from "@hel/ui/switch"
export function SwitchDemo() {When to use it#
Use a switch for a setting that takes effect the moment it is flipped: notifications, dark mode, a feature flag. If the choice only counts after the person presses a save button, a Checkbox is the better fit, because it signals "pending" rather than "live".
Import#
import { Switch, SwitchLabel } from "@hel/ui/switch"Anatomy#
A Switch and its SwitchLabel go inside one label element. That makes the whole row clickable, and links the text to the switch without any id or htmlFor. Mark the label group so the text can follow the disabled state of the switch.
<label className="group flex items-center gap-3">
<Switch defaultChecked />
<SwitchLabel>Email me about new comments</SwitchLabel>
</label>Without a visible label, give the switch an aria-label.
Examples#
A settings list#
Keep the value in state with checked and onCheckedChange when something else on the page depends on it. Leave both out and use defaultChecked when the switch can look after itself.
push
import * as React from "react"
import { Stack } from "@hel/ui/stack"Sizes and states#
size is md by default, or sm for denser lists. A disabled switch cannot be changed, and its label is dimmed along with it. You do not set anything on SwitchLabel for that.
import { Stack } from "@hel/ui/stack"
import { Switch, SwitchLabel } from "@hel/ui/switch"
In a form#
Give the switch a name and it is submitted with the form. When it is on, the form receives its value, which is "on" unless you set another. required marks the switch as needed.
The thumb slides in the direction people read, so the switch flips on its own in right-to-left languages.
Props#
Switch#
| Prop | Type | Default |
|---|---|---|
checked / defaultChecked | boolean | false |
onCheckedChange | (checked: boolean) => void | none |
size | "md" | "sm" | "md" |
disabled / readOnly / required | boolean | false |
name / value | string | none / "on" |
It also takes every prop of the Base UI switch.
SwitchLabel#
The text next to the switch. It takes the props of a span.