# Switch

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

## Installation

```bash
npx shadcn@latest add https://reactdocs.canceydejean.dev/r/switch.json
```

[Registry JSON](https://reactdocs.canceydejean.dev/r/switch.json)

## Preview

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

export function Preview() {
  return (
    <div className="flex items-center gap-2">
      <Switch id="preview-airplane" defaultChecked />
      <label htmlFor="preview-airplane" className="text-sm leading-none font-medium">
        Airplane Mode
      </label>
    </div>
  );
}
```


## Source

### switch.tsx

```tsx
"use client";

import { Switch as SwitchPrimitive } from "@base-ui/react/switch";

import { cn } from "cn";

function Switch({
  className,
  size = "default",
  ...props
}: SwitchPrimitive.Root.Props & {
  size?: "sm" | "default";
}) {
  return (
    <SwitchPrimitive.Root
      data-slot="switch"
      data-size={size}
      className={cn(
        "peer group/switch focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:ring-3 aria-invalid:ring-3 data-disabled:cursor-not-allowed data-disabled:opacity-50 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px]",
        className,
      )}
      {...props}
    >
      <SwitchPrimitive.Thumb
        data-slot="switch-thumb"
        className="bg-background dark:data-checked:bg-primary-foreground dark:data-unchecked:bg-foreground pointer-events-none block rounded-full ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0"
      />
    </SwitchPrimitive.Root>
  );
}

export { Switch };
```



## Usage

Use switches for binary settings. Pair with a label via `htmlFor` matching the switch `id`.

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

export function Example() {
  return (
    <div className="flex items-center gap-2">
      <Switch id="airplane-mode" />
      <label htmlFor="airplane-mode">Airplane Mode</label>
    </div>
  );
}
```

Supports `size` (`default` | `sm`), controlled `checked` / `onCheckedChange`, `disabled`, and
`aria-invalid`. Built on Base UI Switch.

