Toggle

A two-state button that can be either on or off.

Features

  • Full keyboard navigation
  • Can be controlled or uncontrolled

Anatomy

  • Toggle: The toggle component

Usage

To create a toggle, use the createToggle builder function. Follow the anatomy or the example above to create your toggle.

Disabling the toggle

To disable a the toggle, set the disabled argument to true.

    <script lang="ts">
  import { createToggle } from '@melt-ui/svelte'
 
  const { toggle, pressed, disabled } = createToggle({
    disabled: true
  })
  // or
  disabled.set(true)
  // or
  disabled.update((d) => !d)
</script>

Controlled access

To programmatically control the Toggle, you can directly set the pressed store. you can also directly set the disabled store.

    <script lang="ts">
  import { createToggle } from '@melt-ui/svelte'
 
  export let pressed = true
  export let disabled = false
 
  const { pressed: pressedStore, disabled: disabledStore } = createToggle({
    pressed,
    disabled
  })
 
  $: pressedStore.set(pressed)
  pressedStore.subscribe((v) => (pressed = v))
 
  $: disabledStore.set(pressed)
  disabledStore.subscribe((v) => (disabled = v))
</script>

API Reference

createToggle

Props

Prop Default Type / Description
disabled false
boolean

Whether or not the toggle is disabled.

pressed false
boolean

Whether or not the toggle is pressed.

Returned Props

Returned Prop Type Description
pressed
Writable<boolean>

A writable store that controls the pressed state of the toggle.

disabled
Writable<boolean>

A writable store that controls whether or not the toggle is disabled.

root
-

The builder store used to create the toggle root.

root

Data Attributes

Data Attribute Value
[data-disabled]

Present when the toggle is disabled.

[data-state]

'on' | 'off'

[data-melt-toggle]

Present on all toggle elements.

Accessibility

Adheres to the Button WAI-ARIA design pattern

Key Behavior
Space

Activates/deactivates the toggle.

Enter

Activates/deactivates the toggle.