# Switch

Turns a setting on or off, taking effect at once.

An on/off toggle that takes effect immediately. The track fills with ink when on and the thumb travels across; pressing squeezes the thumb. It is a native button with role=switch, so state lives in aria-checked and no engine is needed. An optional label wrapper makes the text part of the hit area.

Kind: component · Category: Inputs · Status: stable · Targets: React, Vue, Svelte

## Add

```bash
npx fndn add switch
```

It writes the folder `switch/` into the project's ui folder (`index.ts`, `switch.tsx`, `Switch.vue`, `Switch.svelte`, `switch.recipe.ts`). First time: [Installation](/installation.md).

## Usage

```tsx
import { Switch } from "@/components/ui/switch";
```

```vue
import { Switch } from "@/components/ui/switch";
```

```svelte
import { Switch } from "$lib/components/ui/switch";
```

## Parts

In the DOM the root carries `data-slot="switch"` and each part `data-slot="switch-<part>"`; in the recipe the root is the `base` slot and each part a slot named after it in camelCase.

| Part | Element | data-slot | Flags | Notes |
| --- | --- | --- | --- | --- |
| `root` | `button` | `switch` |  | role=switch; aria-checked Wrapper rule: class and style land on this outermost element (what a caller sizes and places); every other attribute stays on the control. |
| `thumb` | `span` | `switch-thumb` |  | Travels on translate, squeezes on scale while pressed. Carries kbd-instant. |
| `label` | `label` | `switch-label` | optional | Wraps the switch and its text; a click on the text toggles and the text is the accessible name. In the adapters it is rendered when there is a visible label, and `class` and `style` then land on it (the outermost element: what a caller sizes and places); every other attribute stays on the button. |
| `label-text` | `span` | `switch-label-text` | optional |  |

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `checked` | `boolean` | `false` | Bindable (React: `defaultChecked` and `onCheckedChange`; Vue: `v-model:checked`; Svelte: `bind:checked`).  |
| `size` | `"sm" \| "md"` | `"md"` | md: 40×24. sm: 32×18. |
| `disabled` | `boolean` | `false` |  |
| `label` | `string` |  | Accessible name when there is no visible label. |

Other attributes and `class` go to the root; `class` is merged through the recipe.

## Events

| Event | Payload |
| --- | --- |
| `checkedChange` | (checked: boolean) after a toggle |

## Slots

| Slot | Content |
| --- | --- |
| `default` | Visible label. When given, the switch is wrapped in the label part. |

## States

`checked`, `hover`, `press`, `focus-visible`, `disabled`

## Keyboard and accessibility

Role: switch.

Keyboard:

- Space / Enter toggle

Notes:

- Name it with the label wrapper, aria-labelledby, or the label prop (aria-label).
- State is aria-checked, which is also what the recipe keys on.
- A toggle from the keyboard moves the thumb instantly.
- To set it from outside, control `checked`: React checked / onCheckedChange, Vue v-model:checked, Svelte bind:checked.

## Motion

- thumb: translate over duration.move with easing.move (pointer only)
- press (pointer only): thumb scales to motion.press-scale-sm over duration.press with easing.out-strong; none from Space / Enter
- track: colour over duration.base

## Tokens

`color.ink`, `color.ink-3`, `color.on-ink`, `color.on-accent`, `color.line-strong`, `radius.pill`, `text.sm`, `duration.base`, `duration.move`, `duration.press`, `easing.move`, `easing.out-strong`, `motion.press-scale-sm`

## Examples

### Deploy on push

React · `deploy-on-push.tsx`

```tsx
import { useState } from "react";
import { Switch } from "@/components/ui/switch";

/* a settings row: name and effect at the start, the switch at the end; it applies at once */
export default function DeployOnPush() {
  const [enabled, setEnabled] = useState(true);
  return (
    <div className="flex w-80 items-start justify-between gap-4">
      <div className="flex flex-col gap-0.5">
        <p id="deploy-on-push" className="text-sm font-medium text-ink">Deploy on push</p>
        <p id="deploy-on-push-help" className="text-sm text-ink-2">
          {enabled ? "Every push to main deploys web-app to Production." : "Deploy web-app by hand from the Deploys tab."}
        </p>
      </div>
      <Switch checked={enabled} onCheckedChange={setEnabled} aria-labelledby="deploy-on-push" aria-describedby="deploy-on-push-help" />
    </div>
  );
}
```

Vue · `deploy-on-push.vue`

```vue
<script setup lang="ts">
import { ref } from "vue";
import { Switch } from "@/components/ui/switch";

/* a settings row: name and effect at the start, the switch at the end; it applies at once */
const enabled = ref(true);
</script>

<template>
  <div class="flex w-80 items-start justify-between gap-4">
    <div class="flex flex-col gap-0.5">
      <p id="deploy-on-push" class="text-sm font-medium text-ink">Deploy on push</p>
      <p id="deploy-on-push-help" class="text-sm text-ink-2">
        {{ enabled ? "Every push to main deploys web-app to Production." : "Deploy web-app by hand from the Deploys tab." }}
      </p>
    </div>
    <Switch v-model:checked="enabled" aria-labelledby="deploy-on-push" aria-describedby="deploy-on-push-help" />
  </div>
</template>
```

Svelte · `deploy-on-push.svelte`

```svelte
<script lang="ts">
  import { Switch } from "$lib/components/ui/switch";

  /* a settings row: name and effect at the start, the switch at the end; it applies at once */
  let enabled = $state(true);
</script>

<div class="flex w-80 items-start justify-between gap-4">
  <div class="flex flex-col gap-0.5">
    <p id="deploy-on-push" class="text-sm font-medium text-ink">Deploy on push</p>
    <p id="deploy-on-push-help" class="text-sm text-ink-2">
      {enabled ? "Every push to main deploys web-app to Production." : "Deploy web-app by hand from the Deploys tab."}
    </p>
  </div>
  <Switch bind:checked={enabled} aria-labelledby="deploy-on-push" aria-describedby="deploy-on-push-help" />
</div>
```

### Notification settings

React · `notifications.tsx`

```tsx
import { useState } from "react";
import { Separator } from "@/components/ui/separator";
import { Switch } from "@/components/ui/switch";

/* a settings list: label at the start, switch at the end of each row */
const settings = [
  { id: "deploy-failed", label: "A deploy fails" },
  { id: "review-requested", label: "Someone requests your review" },
  { id: "weekly-usage", label: "Weekly usage summary for Northwind" },
];

export default function Notifications() {
  const [on, setOn] = useState<Record<string, boolean>>({ "deploy-failed": true, "review-requested": true, "weekly-usage": false });
  return (
    <div className="flex w-80 flex-col">
      {settings.map((s, i) => (
        <div key={s.id}>
          {i > 0 && <Separator className="my-2" />}
          <div className="flex items-center justify-between gap-4">
            <span id={s.id} className="text-sm text-ink">{s.label}</span>
            <Switch size="sm" aria-labelledby={s.id} checked={on[s.id]} onCheckedChange={(v) => setOn({ ...on, [s.id]: v })} />
          </div>
        </div>
      ))}
    </div>
  );
}
```

Vue · `notifications.vue`

```vue
<script setup lang="ts">
import { ref } from "vue";
import { Separator } from "@/components/ui/separator";
import { Switch } from "@/components/ui/switch";

/* a settings list: label at the start, switch at the end of each row */
const settings = [
  { id: "deploy-failed", label: "A deploy fails" },
  { id: "review-requested", label: "Someone requests your review" },
  { id: "weekly-usage", label: "Weekly usage summary for Northwind" },
];

const on = ref<Record<string, boolean>>({ "deploy-failed": true, "review-requested": true, "weekly-usage": false });
</script>

<template>
  <div class="flex w-80 flex-col">
    <div v-for="(s, i) in settings" :key="s.id">
      <Separator v-if="i > 0" class="my-2" />
      <div class="flex items-center justify-between gap-4">
        <span :id="s.id" class="text-sm text-ink">{{ s.label }}</span>
        <Switch v-model:checked="on[s.id]" size="sm" :aria-labelledby="s.id" />
      </div>
    </div>
  </div>
</template>
```

Svelte · `notifications.svelte`

```svelte
<script lang="ts">
  import { Separator } from "$lib/components/ui/separator";
  import { Switch } from "$lib/components/ui/switch";

  /* a settings list: label at the start, switch at the end of each row */
  const settings = [
    { id: "deploy-failed", label: "A deploy fails" },
    { id: "review-requested", label: "Someone requests your review" },
    { id: "weekly-usage", label: "Weekly usage summary for Northwind" },
  ];

  let on = $state<Record<string, boolean>>({ "deploy-failed": true, "review-requested": true, "weekly-usage": false });
</script>

<div class="flex w-80 flex-col">
  {#each settings as s, i (s.id)}
    <div>
      {#if i > 0}<Separator class="my-2" />{/if}
      <div class="flex items-center justify-between gap-4">
        <span id={s.id} class="text-sm text-ink">{s.label}</span>
        <Switch bind:checked={on[s.id]} size="sm" aria-labelledby={s.id} />
      </div>
    </div>
  {/each}
</div>
```

### Password protection per environment (no visible label)

React · `environment-protection.tsx`

```tsx
import { Switch } from "@/components/ui/switch";

/* no visible label in a row: the switch is named by `label` (its aria-label) */
const environments = [
  { name: "Production", protected: true },
  { name: "Staging", protected: true },
  { name: "Preview", protected: false },
];

export default function EnvironmentProtection() {
  return (
    <table className="w-80 text-sm">
      <thead>
        <tr className="text-start text-xs text-ink-2">
          <th className="pb-2 text-start font-medium">Environment</th>
          <th className="pb-2 text-end font-medium">Password</th>
        </tr>
      </thead>
      <tbody>
        {environments.map((env) => (
          <tr key={env.name}>
            <td className="py-1.5 text-ink">{env.name}</td>
            <td className="py-1.5 text-end">
              <Switch size="sm" label={`Password-protect ${env.name}`} defaultChecked={env.protected} />
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}
```

Vue · `environment-protection.vue`

```vue
<script setup lang="ts">
import { ref } from "vue";
import { Switch } from "@/components/ui/switch";

/* no visible label in a row: the switch is named by `label` (its aria-label) */
const environments = ref([
  { name: "Production", protected: true },
  { name: "Staging", protected: true },
  { name: "Preview", protected: false },
]);
</script>

<template>
  <table class="w-80 text-sm">
    <thead>
      <tr class="text-start text-xs text-ink-2">
        <th class="pb-2 text-start font-medium">Environment</th>
        <th class="pb-2 text-end font-medium">Password</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="env in environments" :key="env.name">
        <td class="py-1.5 text-ink">{{ env.name }}</td>
        <td class="py-1.5 text-end">
          <Switch v-model:checked="env.protected" size="sm" :label="`Password-protect ${env.name}`" />
        </td>
      </tr>
    </tbody>
  </table>
</template>
```

Svelte · `environment-protection.svelte`

```svelte
<script lang="ts">
  import { Switch } from "$lib/components/ui/switch";

  /* no visible label in a row: the switch is named by `label` (its aria-label) */
  let environments = $state([
    { name: "Production", protected: true },
    { name: "Staging", protected: true },
    { name: "Preview", protected: false },
  ]);
</script>

<table class="w-80 text-sm">
  <thead>
    <tr class="text-start text-xs text-ink-2">
      <th class="pb-2 text-start font-medium">Environment</th>
      <th class="pb-2 text-end font-medium">Password</th>
    </tr>
  </thead>
  <tbody>
    {#each environments as env (env.name)}
      <tr>
        <td class="py-1.5 text-ink">{env.name}</td>
        <td class="py-1.5 text-end">
          <Switch bind:checked={env.protected} size="sm" label={`Password-protect ${env.name}`} />
        </td>
      </tr>
    {/each}
  </tbody>
</table>
```

### Only the owner can change it (disabled)

React · `owner-only.tsx`

```tsx
import { Switch } from "@/components/ui/switch";

/* disabled keeps its state readable and says who can change it */
export default function OwnerOnly() {
  return (
    <div className="flex max-w-80 flex-col gap-2">
      <Switch checked disabled aria-describedby="two-factor-help">
        Require two-factor authentication
      </Switch>
      <p id="two-factor-help" className="text-sm text-ink-2">Only Maya Chen, the workspace owner, can change this.</p>
    </div>
  );
}
```

Vue · `owner-only.vue`

```vue
<script setup lang="ts">
import { Switch } from "@/components/ui/switch";
</script>

<!-- disabled keeps its state readable and says who can change it -->
<template>
  <div class="flex max-w-80 flex-col gap-2">
    <Switch checked disabled aria-describedby="two-factor-help">Require two-factor authentication</Switch>
    <p id="two-factor-help" class="text-sm text-ink-2">Only Maya Chen, the workspace owner, can change this.</p>
  </div>
</template>
```

Svelte · `owner-only.svelte`

```svelte
<script lang="ts">
  import { Switch } from "$lib/components/ui/switch";
</script>

<!-- disabled keeps its state readable and says who can change it -->
<div class="flex max-w-80 flex-col gap-2">
  <Switch checked disabled aria-describedby="two-factor-help">Require two-factor authentication</Switch>
  <p id="two-factor-help" class="text-sm text-ink-2">Only Maya Chen, the workspace owner, can change this.</p>
</div>
```

## Recipe

`switch.recipe.ts`:

```ts
import { tv, type VariantProps } from "../lib/tv";

/* switch — a native button with role=switch. State lives in aria-checked, so the same markup works
 * in every target.   md 40×24 · 20px thumb     sm 32×18 · 14px thumb
 *
 * Everything is here, motion included: the track's colour, the thumb's travel on `translate` and its
 * squeeze on `scale` (two properties, so each keeps its own timing: travel is on-screen movement,
 * the squeeze is press feedback). Parts are found by data-slot (switch, switch-thumb, switch-label,
 * switch-label-text); the root slot is `base`. */

/* `switch` is a reserved word, hence the name */
export const switchRecipe = tv({
  slots: {
    base: [
      "relative inline-block shrink-0 rounded-pill bg-line-strong",
      "aria-checked:bg-ink",
      "hover:bg-[color-mix(in_oklch,var(--fndn-line-strong)_70%,var(--fndn-ink-3))] aria-checked:hover:bg-ink aria-checked:hover:opacity-90",
      "disabled:opacity-50 disabled:cursor-default disabled:pointer-events-none",
      "aria-disabled:opacity-50 aria-disabled:cursor-default aria-disabled:pointer-events-none",
      /* the track and the thumb answer a key together: both instant */
      "motion-colors-base motion-opacity-base kbd-instant",
    ],
    /* right-to-left the switch mirrors: off at the right, on at the left. on-ink keeps the thumb
     * visible in both themes (in dark mode the track is near white). */
    thumb: [
      "kbd-instant",
      "absolute top-0.5 start-0.5 rounded-[50%] bg-on-accent shadow-[0_1px_2px_oklch(0_0_0/0.2)]",
      "[[data-slot=switch][aria-checked=true]_&]:bg-on-ink",
      "motion-colors-base motion-transform-glide motion-also-[scale_var(--fndn-duration-press)_var(--fndn-easing-out-strong)]",
      /* press: the small-control token, pointer only (Space and Enter also make the button :active,
       * and keyboard changes are instant), like the checkbox box and the radio */
      "[:root:not([data-fndn-input=keyboard])_[data-slot=switch]:active_&]:squeeze-press-sm",
    ],
    /* optional label wrapper: the text is part of the hit area and names the switch. The label line
     * is 18px, padded to the switch's height, so the switch and the first text line share one
     * centre line and a wrapped label keeps the switch on line one (as the checkbox and the radio do). */
    label: [
      "inline-flex items-start gap-2 min-w-0 max-w-full text-sm leading-[18px] text-ink cursor-pointer",
      "select-none touch-manipulation [-webkit-touch-callout:none] has-[>[data-slot=switch]:disabled]:cursor-default",
    ],
    /* author text reads in its own direction; the alignment stays on the page's side */
    labelText: [
      "min-w-0 [overflow-wrap:anywhere] py-[3px] [unicode-bidi:plaintext]",
      "[&:dir(ltr)]:text-left [&:dir(rtl)]:text-right [[data-slot=switch]:disabled+&]:text-ink-3",
    ],
  },
  variants: {
    size: {
      /* the thumb travels the track less its own width and the two 2px insets; mirrored right-to-left */
      sm: {
        base: "w-8 h-[18px]",
        thumb: "size-3.5 [[data-slot=switch][aria-checked=true]_&]:translate-x-3.5 [[data-slot=switch][aria-checked=true]:dir(rtl)_&]:-translate-x-3.5",
        labelText: "py-0",
      },
      md: { base: "w-10 h-6", thumb: "size-5 [[data-slot=switch][aria-checked=true]_&]:translate-x-4 [[data-slot=switch][aria-checked=true]:dir(rtl)_&]:-translate-x-4" },
    },
  },
  defaultVariants: { size: "md" },
});

export type SwitchRecipeProps = VariantProps<typeof switchRecipe>;
```
