---
title: Switch
description: Toggle an on/off setting with switch semantics and form values.
package: moraine
version: 0.11.0
repository: https://github.com/subframe7536/moraine
---

# Switch

> Toggle an on/off setting with switch semantics and form values.

## Anatomy

```text
Switch [component; slot=root]
├── input [internal]
├── track [slot]
│   └── thumb [slot]
│       └── icon [slot]
└── wrapper [slot]
    ├── label [slot]
    └── description [slot]
```

## Usage

Use Switch for an on/off setting whose state is immediately meaningful. For an independent form
choice that may be part of a set, use [Checkbox](https://moraine.subf.dev/components/checkbox.md). For a pressed command
button, use [ToggleButton](https://moraine.subf.dev/components/toggle-button.md).

```tsx
import { Switch } from 'moraine'

export function Example() {
  return <Switch label="Notifications" />
}
```

### Checked state and forms

The focusable button has `role="switch"`; a hidden checkbox handles native form submission. Use
`checked` with `onCheckedChange` for controlled state, or `defaultChecked` for an initial value.
`onCheckedChange` fires only when the user toggles the switch, not for programmatic `checked`
changes or while the switch is `disabled`, `readOnly`, or `loading`.

`trueValue` and `falseValue` map checked state to domain values for `checked`, callbacks, and
schema-bound forms. Native form submission uses the separate `value` prop (default `'on'`) under
`name` only while checked; an unchecked switch contributes no entry.

```tsx
<Switch
  checked={enabled()}
  onCheckedChange={setEnabled}
  label="Airplane mode"
/>
<Switch trueValue="enabled" falseValue="disabled" label="Deployment gate" />
```

### Loading ownership

While `loading` is set, the switch is non-interactive and shows `loadingIcon` on the thumb in place
of `checkedIcon` or `uncheckedIcon`. Drive `loading` from the application; the switch does not start
or track the async operation itself.

```tsx
<Switch
  checked={checked()}
  onCheckedChange={handleToggle}
  loading={pending()}
  label="Auto-deploy changes"
/>
```

## Examples

### Toggle deploy protection

Keep the setting in local state with `checked` and `onCheckedChange`. Use `defaultChecked` only
when the switch owns its initial value.

```tsx
import { Switch } from 'moraine'
import { createSignal } from 'solid-js'

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

  return (
    <div class="flex flex-col gap-3 max-w-xl">
      <Switch
        label="Email alerts"
        description="Uncontrolled"
        defaultChecked
        checkedIcon="i-lucide-bell"
        uncheckedIcon="i-lucide-bell-off"
      />
      <Switch
        label="Deploy protection"
        description={`Current: ${checked() ? 'enabled' : 'disabled'}`}
        checked={checked()}
        onCheckedChange={setChecked}
        checkedIcon="i-lucide-shield-check"
        uncheckedIcon="i-lucide-shield"
      />
    </div>
  )
}
```

### Store a deployment gate as domain values

Map on and off to application strings with `trueValue` and `falseValue`. Callbacks then receive
those strings instead of booleans.

```tsx
import { Switch } from 'moraine'
import { createSignal } from 'solid-js'

export function CustomTrueFalseValues() {
  const [deploymentGuard, setDeploymentGuard] = createSignal<'enabled' | 'disabled'>('disabled')

  return (
    <div class="max-w-xl space-y-3">
      <Switch<'enabled', 'disabled'>
        label="Deployment gate"
        description="Domain value binding"
        trueValue="enabled"
        falseValue="disabled"
        checked={deploymentGuard()}
        onCheckedChange={setDeploymentGuard}
        checkedIcon="i-lucide-check-check"
        uncheckedIcon="i-lucide-x"
      />
      <p class="text-xs text-muted-foreground">Current value: {deploymentGuard()}</p>
    </div>
  )
}
```

### Show a pending auto-deploy

Drive `loading` from the in-flight request. The switch does not start an async operation by itself.

```tsx
import { Switch } from 'moraine'
import { createSignal } from 'solid-js'

export function LoadingState() {
  const [loading, setLoading] = createSignal(false)
  const [checked, setChecked] = createSignal(false)

  const handleToggle = (next: boolean) => {
    setLoading(true)
    setTimeout(() => {
      setChecked(next)
      setLoading(false)
    }, 1000)
  }

  return (
    <div class="max-w-md w-full">
      <Switch
        checked={checked()}
        onCheckedChange={handleToggle}
        loading={loading()}
        label="Auto-deploy changes"
        description="Trigger production build on git push."
      />
    </div>
  )
}
```

### Mark on and off with icons

Pass `checkedIcon` and `uncheckedIcon` to show a mark on the thumb for each state. Loading still
comes from application state.

```tsx
import { Switch } from 'moraine'

export function LoadingIcons() {
  return (
    <div class="max-w-sm space-y-3">
      <Switch
        checked
        loading
        label="Sync preferences"
        description="The visual loading state is supplied by the application."
        checkedIcon="i-lucide:cloud-check"
        uncheckedIcon="i-lucide:cloud-off"
      />
      <Switch
        defaultChecked
        label="Use dark theme"
        checkedIcon="i-lucide:moon"
        uncheckedIcon="i-lucide:sun"
      />
    </div>
  )
}
```

### Save auto-renewal

Bind the switch to `form.Field` so submit reads a boolean from the schema.

```tsx
import { Button, createForm, Switch } from 'moraine'
import { createSignal } from 'solid-js'
import * as v from 'valibot'

export function FormIntegration() {
  const [submittedAutoRenew, setSubmittedAutoRenew] = createSignal(true)
  const form = createForm({
    schema: v.object({
      autoRenew: v.boolean(),
    }),
    initialInput: { autoRenew: true },
    validate: 'input',
  })

  return (
    <form.Form onSubmit={(output) => setSubmittedAutoRenew(output.autoRenew)}>
      <div class="max-w-xl space-y-4">
        <form.Field
          name="autoRenew"
          label="Subscription Settings"
          description="Automatically renew monthly billing at the end of the billing cycle."
        >
          <Switch label="Enable monthly auto-renewal" />
        </form.Field>
        <div class="flex gap-3 items-center">
          <Button type="submit" variant="soft" tone="neutral" size="sm">
            Save Preferences
          </Button>
          <p class="text-xs text-muted-foreground">
            Auto-renew: {submittedAutoRenew() ? 'Enabled' : 'Disabled'}
          </p>
        </div>
      </div>
    </form.Form>
  )
}
```

## API Reference

### Attributes

| Attributes | Slot | Description |
| --- | --- | --- |
| `data-checked` | `switch`, `switch-track`, `switch-thumb`, `switch-icon` | Present when the item or toggle is checked. |
| `data-disabled` | `switch`, `switch-track`, `switch-thumb` | Present when the component, slot, or item is disabled. |
| `data-invalid` | `switch`, `switch-track` | Present when the field or form has a validation error. |
| `data-loading` | `switch`, `switch-icon` | Present when the component or async operation is loading. |
| `data-readonly` | `switch`, `switch-track` | Present when the field is in read-only mode. |
| `data-required` | `switch`, `switch-label` | Present when the field input is required. |
| `data-unchecked` | `switch`, `switch-track`, `switch-thumb`, `switch-icon` | Present when the checkbox, radio item, or switch is unchecked. |

### Props

Props for the Switch component.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| checked | TTrue \| TFalse \| undefined | — | Whether the switch is checked (controlled). Accepts `trueValue`, `falseValue`, or a boolean.<br>Leave it `undefined` for uncontrolled usage. |
| checkedIcon | IconT.Name \| undefined | — | Icon shown on the thumb when the switch is checked. No icon is rendered when omitted. |
| defaultChecked | boolean \| undefined | — | Whether the switch is initially checked (uncontrolled). Form reset returns to this state. |
| description | JSX.Element \| undefined | — | Description shown with the label and linked to the control as its accessible description. |
| disabled | boolean \| undefined | false | Whether the control is disabled: it cannot be interacted with and sets `aria-disabled`.<br>When omitted, the control inherits `disabled` from the surrounding `Field`; an explicit<br>`false` overrides the `Field`. |
| falseValue | TFalse \| undefined | false | Value that `onCheckedChange` receives when the switch becomes unchecked, and that `checked`<br>accepts for the unchecked state. |
| form | string \| undefined | — | The id of a `<form>` the hidden input belongs to, instead of the closest<br>ancestor form. |
| id | string \| undefined | — | The ID of the control's main focusable element, which a surrounding `Field` label points to<br>with `for`. A unique ID is generated when omitted. The control's related parts (hidden<br>input, label, description) derive their IDs from it, so keep it unique on the page. |
| inputRef | Ref<HTMLInputElement> \| undefined | — | Receives the hidden `<input type="checkbox">` that submits the switch with a form. |
| label | JSX.Element \| undefined | — | Label for the switch. It is a `<label>` for the control and its accessible name unless the<br>surrounding `Field` provides one. |
| loading | boolean \| undefined | false | Whether the switch is in a loading state. A loading switch is disabled and shows `loadingIcon`<br>on the thumb in place of the checked or unchecked icon. |
| loadingIcon | IconT.Name \| undefined | 'icon-loading' | Icon shown on the thumb while `loading` is set. |
| name | string \| undefined | — | The name of the control, used for native form submission. When omitted, the control uses<br>the name of its form binding or a string `name` set on the surrounding `Field`. |
| onCheckedChange | ((value: TTrue \| TFalse) => void) \| undefined | — | Called when the user toggles the switch, with `trueValue` (checked) or `falseValue`<br>(unchecked), which are `true` and `false` by default. It does not fire for programmatic<br>changes to `checked`, or while the switch is `disabled`, `readOnly`, or `loading`. |
| onPointerDown | JSX.EventHandlerUnion<HTMLButtonElement, PointerEvent> \| undefined | — | Pointer down handler for the switch track (the `role="switch"` button). It runs before the<br>switch's own handling; call `event.preventDefault()` to skip that. |
| readOnly | boolean \| undefined | false | Whether the control is read-only: the value is visible and focusable but cannot be changed,<br>and `aria-readonly` is set. When omitted, the control inherits `readOnly` from the<br>surrounding `Field`. |
| required | boolean \| undefined | false | Whether the control is required, which sets `aria-required` (and the native `required`<br>attribute where the control renders a native input). When omitted, the control inherits<br>`required` from the surrounding `Field`. |
| size | 'sm' \| 'md' \| 'lg' \| undefined | 'md' | Visual size of the component. |
| trueValue | TTrue \| undefined | true | Value that `onCheckedChange` receives when the switch becomes checked, and that `checked`<br>accepts for the checked state. Use it to map the state to a domain value. |
| uncheckedIcon | IconT.Name \| undefined | — | Icon shown on the thumb when the switch is unchecked. No icon is rendered when omitted. |
| value | string \| undefined | 'on' | Native value of the hidden checkbox, submitted under `name` when the switch is checked. Nothing<br>is submitted while it is unchecked. This is separate from `trueValue`, which is what callbacks receive. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| classes | Classes \| undefined | — | Family slot class defaults for this instance. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |
| styles | Styles \| undefined | — | Family slot style defaults for this instance. |

**`trueValue` example**

```tsx
import { Switch } from 'moraine'

<Switch
  label="Theme"
  trueValue="dark"
  falseValue="light"
  defaultChecked
  onCheckedChange={(mode) => console.log(mode)}
/>
```
