Forms

Switch

Toggle a setting.

Switch

Toggle a setting.

Form

Visible to your team.

Install

Install
npx shadcn@latest add http://localhost:3000/r/switch.json

Usage

switch-example.tsx
"use client"

import { useState } from "react"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"

export function Example() {
  const [switchOn, setSwitchOn] = useState(false)
  return (
    <div className="flex w-full max-w-xs items-center justify-between gap-4 rounded-xl border p-3">
      <div>
        <Label htmlFor="showcase-switch">Public profile</Label>
        <p className="mt-1 text-xs text-muted-foreground">
          Visible to your team.
        </p>
      </div>
      <Switch
        id="showcase-switch"
        checked={switchOn}
        onCheckedChange={setSwitchOn}
      />
    </div>
  )
}

API

Switch
TypeScript
function Switch(props: SwitchPrimitive.Root.Props & {
  size?: "sm" | "default"
})
Source code +
components/ui/switch.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 relative inline-flex shrink-0 items-center rounded-2xl border-2 transition-all outline-none group-has-[:focus-visible]/field-label:ring-0 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-5 data-[size=default]:w-8 data-[size=sm]:h-4 data-[size=sm]:w-6 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:border-primary data-checked:bg-primary group-has-[:focus-visible]/field-label:data-checked:border-primary data-unchecked:border-transparent data-unchecked:bg-input/90 group-has-[:focus-visible]/field-label:data-unchecked:border-transparent data-disabled:cursor-not-allowed data-disabled:opacity-50",
        className
      )}
      {...props}
    >
      <SwitchPrimitive.Thumb
        data-slot="switch-thumb"
        className="pointer-events-none block rounded-2xl bg-background shadow-sm ring-0 transition-transform not-dark:bg-clip-padding group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 data-checked:translate-x-[calc(100%-4px)] dark:data-checked:bg-primary-foreground data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"
      />
    </SwitchPrimitive.Root>
  )
}

export { Switch }

Registry JSON ↗