Skip to main content

Switch

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

Receive a notification when a deployment completes.
Props
Slots

Anatomy#

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. For a pressed command button, use ToggleButton.

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.

<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.

<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.

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.

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.

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.

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.

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
data-checked
Slot: switchswitch-trackswitch-thumbswitch-icon
Description: Present when the item or toggle is checked.
data-disabled
Slot: switchswitch-trackswitch-thumb
Description: Present when the component, slot, or item is disabled.
data-invalid
Slot: switchswitch-track
Description: Present when the field or form has a validation error.
data-loading
Slot: switchswitch-icon
Description: Present when the component or async operation is loading.
data-readonly
Slot: switchswitch-track
Description: Present when the field is in read-only mode.
data-required
Slot: switchswitch-label
Description: Present when the field input is required.
data-unchecked
Slot: switchswitch-trackswitch-thumbswitch-icon
Description: Present when the checkbox, radio item, or switch is unchecked.

Props#

Props for the Switch component. Renders a <div> element by default.

Prop