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

export function SwitchExample() {
  return (
    <div className="flex items-center gap-4">
      <Switch />
    </div>
  );
}

Examples

Default checked

Use defaultChecked to set the initial state without controlling the component.

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

export function SwitchCheckedExample() {
  return (
    <div className="flex items-center gap-4">
      <Switch defaultChecked />
    </div>
  );
}

Disabled

Use the disabled prop to prevent interaction.

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

export function SwitchDisabledExample() {
  return (
    <div className="flex items-center gap-4">
      <Switch disabled />
      <Switch defaultChecked disabled />
    </div>
  );
}

Controlled

Manage the checked state with React state using checked and onCheckedChange.

Off
import { useState } from "react";
import { Switch } from "@registry/components/ui/switch";

export function SwitchControlledExample() {
  const [checked, setChecked] = useState(false);

  return (
    <div className="flex items-center gap-4">
      <Switch checked={checked} onCheckedChange={setChecked} />
      <span className="text-sm text-gray-600 dark:text-gray-400">{checked ? "On" : "Off"}</span>
    </div>
  );
}

Installation

Copy the source code below into your project:

import { Switch as BaseSwitch } from "@base-ui/react/switch";
import { cn } from "@registry/lib/utils";

function Switch({ className, ...props }: BaseSwitch.Root.Props) {
  return (
    <BaseSwitch.Root
      className={cn(
        "group/switch inline-flex h-4.5 w-7.5 shrink-0 items-center rounded-full p-px transition-all outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-checked:bg-accent data-unchecked:bg-muted",
        className,
      )}
      data-slot="switch"
      {...props}
    >
      <BaseSwitch.Thumb
        className={cn(
          "pointer-events-none block size-4 rounded-full bg-white shadow-sm transition-[translate,width] group-active/switch:w-4.5 data-checked:translate-x-3 data-checked:group-active/switch:translate-x-2.5 data-unchecked:translate-x-0",
        )}
        data-slot="switch-thumb"
      />
    </BaseSwitch.Root>
  );
}

export { Switch };

API Reference

Switch

This component does not add any props on top of Base UI Switch.Root . See the Base UI docs for the full API reference.