Switch
The Switch component provides a toggle control that allows users to turn a setting on or off. It’s commonly used for binary choices like enabling or disabling features.
Usage
<script>
import { Switch } from "$lib/components/ui/switch";
</script>
<Switch />
Examples
Basic Switch
A simple switch that can be toggled on or off.
Switch with Label
A switch with an associated label for better accessibility.
Checked State
A switch in its checked (on) state.
Disabled State
A switch that cannot be interacted with.
Multiple Switches
A list of switches for multiple settings.
Connect to nearby Wi-Fi networks.
Allow Bluetooth connections.
Disable all wireless connections.
Form Example
Using switches in a form with a submit button.
API Reference
Properties
Property | Type | Default | Description |
---|---|---|---|
checked | boolean | false | Whether the switch is checked (on). |
onCheckedChange | function | undefined | Function called when the checked state changes. |
disabled | boolean | false | When true , prevents the user from interacting with the switch. |
required | boolean | false | When true , indicates that the user must check this switch before the form can be submitted. |
name | string | undefined | The name of the switch when used in a form. |
value | string | undefined | The value of the switch when used in a form. |
class | string | undefined | Additional CSS classes to apply to the switch. |
ref | HTMLButtonElement | null | Reference to the underlying HTML button element. |
Events
The Switch component forwards all standard HTML button events, as it’s based on a button element:
Event | Description |
---|---|
click | Fires when the switch is clicked. |
focus | Fires when the switch receives focus. |
blur | Fires when the switch loses focus. |
change | Fires when the switch state changes. |
Implementation
The Switch component is built on top of bits-ui primitives. It provides smooth transitions between checked and unchecked states, with a sliding thumb element:
// Switch Root styling
"focus-visible:ring-ring focus-visible:ring-offset-background data-[state=checked]:bg-primary data-[state=unchecked]:bg-input peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
// Switch Thumb styling
"bg-background pointer-events-none block size-4 rounded-full shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0"
The component is built with accessibility in mind, supporting keyboard navigation, screen readers, and proper ARIA attributes. The switch provides visual feedback through color changes and movement of the thumb element.