# Switch

On/off control for settings that apply immediately.

Docs: https://corsairui.vercel.app/docs/switch

## Install

```bash
pnpm dlx shadcn@latest add @corsair-ui/switch
```

Also adds: `utils`.
npm: `@radix-ui/react-switch`, `clsx`, `tailwind-merge`.

## API

Built on Radix Switch (https://www.radix-ui.com/primitives/docs/components/switch); its props pass through.

## Styling

Restyle it in the project that installs it: `className` on each part, the theme variables, and these attributes with arbitrary variants (`[&_[data-slot=…]]:…`, `data-[state=…]:…`).

data-slot: `switch`, `switch-thumb`

## Accessibility

- Announced as a switch with its on or off state; Space toggles it.
- For settings that apply at once; inside a submitted form, prefer a checkbox.

## Examples

On the docs page: Default, Settings list. The usage examples in the source comments below are the reference.

## Source

What `shadcn add` writes into the project:

### switch.tsx

```tsx
"use client";

import * as SwitchPrimitive from "@radix-ui/react-switch";
import type { ComponentProps } from "react";

import { cn } from "@/registry/default/lib/utils";

/** For settings that apply immediately. Inside a form that is submitted, prefer a Checkbox. */
function Switch({ className, ...props }: ComponentProps<typeof SwitchPrimitive.Root>) {
  return (
    <SwitchPrimitive.Root
      data-slot="switch"
      className={cn(
        "peer inline-flex h-[1.15rem] w-8 shrink-0 cursor-pointer items-center rounded-full border border-transparent",
        "transition-[color,background-color,box-shadow] outline-none motion-reduce:transition-none",
        "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
        "data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
        "disabled:cursor-not-allowed disabled:opacity-50",
        className
      )}
      {...props}
    >
      <SwitchPrimitive.Thumb
        data-slot="switch-thumb"
        className={cn(
          "bg-background pointer-events-none block size-4 rounded-full ring-0",
          // `translate` is what Tailwind 4 moves; the colour changes with it in dark mode.
          "transition-[transform,translate,background-color] duration-200 ease-out motion-reduce:transition-none",
          "data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0",
          "dark:data-[state=checked]:bg-primary-foreground dark:data-[state=unchecked]:bg-foreground"
        )}
      />
    </SwitchPrimitive.Root>
  );
}

export { Switch };
```
