Switch

A control that allows the user to toggle between checked and not checked.

Features

  • Full keyboard navigation
  • Can be controlled or uncontrolled

Anatomy

  • Root: The root container for the accordion
  • Input: The native HTML input that is visually hidden

Usage

To create a switch, use the createSwitch builder function. You can then reference the anatomy or example above to create your switch.

Disabling the switch

To disable the switch, set the disabled argument as true.

    <script lang="ts">
  import { createSwitch } from '@melt-ui/svelte'
 
  const { root, input, checked, isChecked, options } = createSwitch({
    disabled: true
  })
  // or
  options.update((prev) => ({ ...prev, disabled: true }))
</script>

Controlled access

To programatically control the switch, you can directly set the checked store. You can also update the options store with new arguments.

    <script lang="ts">
  import { createSwitch } from '@melt-ui/svelte'
 
  export let checked = true
  export let disabled = false
 
  const { checked: checkedStore, options } = createSwitch({
    disabled,
    checked
  })
 
  $: checkedStore.set(checked)
  checkedStore.subscribe((v) => (checked = v))
  $: options.update((o) => ({ ...o, disabled }))
</script>

API Reference

createSwitch

Props

Prop Default Type / Description
checked false
boolean

The initial checked state of the switch.

disabled false
boolean

Whether or not the switch is disabled.

required false
boolean

Whether or not the switch is required.

name -
string

The name of the hidden input element used for form submission..

value -
string

The value of the hidden input element used for form submission.

Returned Props

Returned Prop Type Description
options
Writable<CreateSwitchProps>

A writable store that can be used to update the switch props.

checked
Writable<boolean>

A writable store that can be used to update the switch checked state.

isChecked
Readable<boolean>

A derived store that returns whether or not the switch is checked.

root
-

The builder store used to create the switch root.

input
-

The builder store used to create the switch input.

root

Data Attributes

Data Attribute Value
[data-disabled]

Present when the switch is disabled.

[data-state]

'checked' | 'unchecked'

[data-melt-switch]

Present on all switch elements.

input

Data Attributes

Data Attribute Value
[data-melt-switch-input]

Present on all input elements.

Accessibility

Adheres to the Switch WAI-ARIA design pattern

Key Behavior
Space

When the switch has focus, toggles the switch.

Enter

When the switch has focus, toggles the switch.