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.

Privacy Settings

API Reference

Properties

PropertyTypeDefaultDescription
checkedbooleanfalseWhether the switch is checked (on).
onCheckedChangefunctionundefinedFunction called when the checked state changes.
disabledbooleanfalseWhen true, prevents the user from interacting with the switch.
requiredbooleanfalseWhen true, indicates that the user must check this switch before the form can be submitted.
namestringundefinedThe name of the switch when used in a form.
valuestringundefinedThe value of the switch when used in a form.
classstringundefinedAdditional CSS classes to apply to the switch.
refHTMLButtonElementnullReference to the underlying HTML button element.

Events

The Switch component forwards all standard HTML button events, as it’s based on a button element:

EventDescription
clickFires when the switch is clicked.
focusFires when the switch receives focus.
blurFires when the switch loses focus.
changeFires 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.