---
title: Switch for Astro
description: "Astro on/off controls for settings with data-slot state handling."
seo:
    title: Switch for Astro | Shadcn & Tailwind CSS
related:
    - /components/checkbox
    - /components/toggle
sidebar:
    label: "Switch"
---

```astro
---
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
---

<Label class="inline-flex items-center gap-3">
  <Switch name="airplane-mode" />
  Airplane mode
</Label>
```

## Installation

### Command

```sh
bunx --bun shadcn@latest add @gnostic/switch
```

### Manual

Complete the [Installation guide](/docs/installation) first. Then copy the component files below.

Install the component packages:

```sh
bun add @data-slot/switch
```

#### src/components/ui/switch/index.ts

```ts
export { default as Switch } from './switch.astro'
export type { SwitchProps } from './types.ts'
```

#### src/components/ui/switch/switch.astro

```astro
---
import type { HTMLAttributes } from "astro/types"

import { cn } from "cn"
import type { SwitchProps } from "./types.ts"

type Props = HTMLAttributes<"span"> & SwitchProps

const {
  class: className,
  defaultChecked,
  disabled,
  readOnly,
  required,
  name,
  size = "default",
  value,
  uncheckedValue,
  ...props
} = Astro.props

const initialChecked = defaultChecked === true
const switchStyle = "inline-flex h-[calc(var(--thumb-size)+2px)] w-[calc(var(--thumb-size)*2-2px)] shrink-0 items-center rounded-full p-px outline-none transition-[background-color,box-shadow] duration-200 [--thumb-size:--spacing(5)] focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-disabled:cursor-not-allowed data-checked:bg-primary data-unchecked:bg-input data-disabled:opacity-64 sm:[--thumb-size:--spacing(4)] relative data-readonly:cursor-default aria-invalid:ring-destructive/24 peer group/switch"
const switchSizeStyle = {
  sm: "[--thumb-size:--spacing(4)] sm:[--thumb-size:--spacing(3)]",
  default: "",
}
---

<span
  role="switch"
  aria-checked={initialChecked ? "true" : "false"}
  aria-disabled={disabled ? "true" : undefined}
  aria-readonly={readOnly ? "true" : undefined}
  aria-required={required ? "true" : undefined}
  data-slot="switch"
  data-size={size}
  data-checked={initialChecked ? "" : undefined}
  data-unchecked={initialChecked ? undefined : ""}
  data-default-checked={defaultChecked}
  data-disabled={disabled ? "true" : undefined}
  data-read-only={readOnly}
  data-readonly={readOnly ? "" : undefined}
  data-required={required}
  data-name={name}
  data-value={value}
  data-unchecked-value={uncheckedValue}
  class={cn(switchStyle, switchSizeStyle[size], className)}
  {...props}
>
  <span
    aria-hidden="true"
    data-slot="switch-thumb"
    data-checked={initialChecked ? "" : undefined}
    data-unchecked={initialChecked ? undefined : ""}
    class="pointer-events-none block aspect-square h-full origin-left in-[[role=switch]:active,[data-slot=label]:active,[data-slot=field-label]:active]:not-data-disabled:scale-x-110 in-[[role=switch]:active,[data-slot=label]:active,[data-slot=field-label]:active]:rounded-[var(--thumb-size)/calc(var(--thumb-size)*1.1)] rounded-(--thumb-size) bg-background shadow-sm/5 will-change-transform [transition:translate_.15s,border-radius_.15s,scale_.1s_.1s,transform-origin_.15s] data-checked:origin-[var(--thumb-size)_50%] data-checked:translate-x-[calc(var(--thumb-size)-4px)]"
  ></span>
</span>

<script>
  import { create } from "@data-slot/switch"
  import type { SwitchController } from "@data-slot/switch"
  // Destroy bindings before a view transition so the next page-load binds once.
  const controllers: SwitchController[] = []
  const initialize = () => controllers.push(...create())
  initialize()
  document.addEventListener("astro:page-load", initialize)
  document.addEventListener("astro:before-swap", () => {
    for (const controller of controllers) controller.destroy()
    controllers.length = 0
  })
</script>
```

#### src/components/ui/switch/types.ts

```ts
import type { SwitchOptions } from '@data-slot/switch'

/**
 * Switch configuration rendered as data attributes, plus the visual size.
 */
export type SwitchProps = Pick<
    SwitchOptions,
    | 'defaultChecked'
    | 'disabled'
    | 'readOnly'
    | 'required'
    | 'name'
    | 'value'
    | 'uncheckedValue'
> & {
    /**
     * Height of the control.
     *
     * @default "default"
     */
    size?: 'default' | 'sm'
}
```

Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.


## Usage

```astro
---
import { Switch } from "@/components/ui/switch"
---
```

```astro
<Switch />
```

## Examples

```astro
---
import {
  Field,
  FieldContent,
  FieldDescription,
  FieldLabel,
} from "@/components/ui/field"
import { Switch } from "@/components/ui/switch"
---

<div class="w-full max-w-sm">
  <Field orientation="horizontal">
    <Switch id="marketing-emails" name="marketing-emails" defaultChecked />
    <FieldContent>
      <FieldLabel for="marketing-emails">Marketing emails</FieldLabel>
      <FieldDescription>
        Receive occasional updates about new features and product news.
      </FieldDescription>
    </FieldContent>
  </Field>
</div>
```

### With Label

Wrap the whole `Field` in `FieldLabel` to make this card surface activate its switch.

```astro
---
import {
  Field,
  FieldContent,
  FieldDescription,
  FieldLabel,
  FieldTitle,
} from "@/components/ui/field"
import { Switch } from "@/components/ui/switch"
---

<div class="w-full max-w-md">
  <FieldLabel class="w-full">
    <Field orientation="horizontal">
      <Switch name="automatic-updates" defaultChecked />
      <FieldContent>
        <FieldTitle>Automatic updates</FieldTitle>
        <FieldDescription>
          Keep your workspace up to date without manual installs.
        </FieldDescription>
      </FieldContent>
    </Field>
  </FieldLabel>
</div>
```

### Disabled

Add the `disabled` prop to the `Switch` component to disable the switch. Add
the `data-disabled` prop to the `Field` component for styling.

```astro
---
import {
  Field,
  FieldContent,
  FieldDescription,
  FieldLabel,
} from "@/components/ui/field"
import { Switch } from "@/components/ui/switch"
---

<div class="w-full max-w-sm">
  <Field orientation="horizontal" data-disabled="true">
    <Switch id="security-alerts" name="security-alerts" disabled />
    <FieldContent>
      <FieldLabel for="security-alerts">Security alerts</FieldLabel>
      <FieldDescription>
        This setting is managed by your organization.
      </FieldDescription>
    </FieldContent>
  </Field>
</div>
```

### Sizes

Use the `size` prop to change the size of the switch.

```astro
---
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
---

<div class="flex flex-col gap-4">
  <Label class="inline-flex items-center gap-3">
    <Switch size="sm" name="switch-size-sm" />
    Small
  </Label>
  <Label class="inline-flex items-center gap-3">
    <Switch size="default" name="switch-size-default" defaultChecked />
    Default
  </Label>
</div>
```

## API Reference

### SwitchProps

<AutoTypeTable path="../../packages/ui/src/components/ui/switch/types.ts" name="SwitchProps" />

See the [data-slot docs](https://github.com/bejamas/data-slot/blob/main/packages/switch/README.md) for more information on interactivity.

### Events

Dispatch these events on the switch root. The root emits the outbound events.

#### Outbound events

| Event           | Detail                 |
| --------------- | ---------------------- |
| `switch:change` | `{ checked: boolean }` |

#### Inbound events

| Event        | Detail                 |
| ------------ | ---------------------- |
| `switch:set` | `{ checked: boolean }` |

Read the [installed source](/r/switch.json) for the complete prop types.

## When to use Switch

Use Switch for a setting that has two clear states. Put a visible label beside it and explain when the change takes effect. Use its existing size options to match the surrounding form.

## Keyboard and behavior

The controller supplies switch state and keyboard activation. Your application must save the change and handle any failure. Do not imply that a remote setting is saved only because the thumb moved.

## Theme and layout

The checked track uses the primary token and the thumb moves within the control. Check disabled and invalid states with nearby help text. Keep the label outside the moving thumb.
