Toggle

A control element that switches between two states, providing a binary choice.

llms.txt
••••
	<script lang="ts">
  import { Toggle } from "bits-ui";
  import LockKeyOpen from "phosphor-svelte/lib/LockKeyOpen";
 
  let unlocked = $state(false);
  const code = $derived(unlocked ? "B1T5" : "••••");
</script>
 
<div
  class="min-h-input rounded-card-sm border-border bg-background-alt shadow-mini flex h-full w-[176px] items-center gap-2 border py-1 pl-[18px] pr-1.5"
>
  <div
    class="font-alt text-end text-[19px] tracking-[13.87px] {unlocked
      ? 'text-foreground'
      : 'text-muted-foreground'}"
  >
    {code}
  </div>
  <Toggle.Root
    aria-label="toggle code visibility"
    class="bg-background-alt hover:bg-muted active:bg-dark-10 data-[state=on]:bg-muted data-[state=off]:text-foreground-alt data-[state=on]:text-foreground active:data-[state=on]:bg-dark-10 inline-flex size-10 items-center justify-center rounded-[9px] transition-all active:scale-[0.98]"
    bind:pressed={unlocked}
  >
    <LockKeyOpen class="size-6" />
  </Toggle.Root>
</div>

Structure

	<script lang="ts">
  import { Toggle } from "bits-ui";
</script>
 
<Toggle.Root />

Managing Pressed State

This section covers how to manage the pressed state of the component.

Two-Way Binding

Use bind:pressed for simple, automatic state synchronization:

	<script lang="ts">
  import { Toggle } from "bits-ui";
  let myPressed = $state(true);
</script>
 
<button onclick={() => (myPressed = false)}> un-press </button>
 
<Toggle.Root bind:pressed={myPressed} />

Fully Controlled

Use a Function Binding for complete control over the state's reads and writes.

	<script lang="ts">
  import { Toggle } from "bits-ui";
  let myPressed = $state(false);
 
  function getPressed() {
    return myPressed;
  }
 
  function setPressed(newPressed: boolean) {
    myPressed = newPressed;
  }
</script>
 
<Toggle.Root bind:pressed={getPressed, setPressed}>
  <!-- ... -->
</Toggle.Root>

API Reference

Toggle.Root

The toggle button.

Property Details
pressed
onPressedChange
disabled
ref
children
child
Data Attribute Details
data-state
data-disabled
data-toggle-root