shadcn.io is not affiliated with official shadcn/ui
Installation
bunx --bun shadcn@latest add https://kit.dev/r/radix/switch.jsonnpx shadcn@latest add https://kit.dev/r/radix/switch.jsonpnpm dlx shadcn@latest add https://kit.dev/r/radix/switch.jsonyarn shadcn@latest add https://kit.dev/r/radix/switch.jsonInstall the following dependencies:
bun add radix-uinpm install radix-uipnpm add radix-uiyarn add radix-uiCopy and paste the following code into your project.
"use client";
import { Switch as SwitchPrimitive } from "radix-ui";
import type React from "react";
import { cn } from "@/lib/utils";
export const Switch = (
props: React.ComponentProps<typeof SwitchPrimitive.Root> & {
size?: "sm" | "default";
}
) => {
const { className, size = "default", ...rest } = props;
return (
<SwitchPrimitive.Root
className={cn(
"cn-switch peer group/switch relative inline-flex items-center outline-none transition-all after:absolute after:-inset-x-3 after:-inset-y-2 data-disabled:cursor-not-allowed data-disabled:opacity-50",
classNameUpdate the import paths to match your project setup.
Anatomy
Switch
├── SwitchLabel
├── SwitchControl
└── SwitchThumbUsage
import { Field, FieldLabel } from "@/components/ui/field";
import { Switch } from "@/components/ui/switch";<Field className="w-fit" orientation="horizontal">
<Switch />
<FieldLabel>Airplane Mode</FieldLabel>
</Field>Accessibility
| Key | Description |
|---|---|
Space | Activate the focused control. |
Demos
Description
Switch with a label and description.
Choice Card
Card-style selection where FieldLabel wraps the entire Field for a clickable card pattern.
Disabled
Add the disabled prop to the Switch and Field to disable the control.
Invalid
Add aria-invalid to the Switch and invalid to the Field for invalid styling.
Sizes
Use the size prop to change the size of the switch.
Rtl
Right-to-left switch. See the RTL configuration guide for document direction.
API Reference
Switch
label
PropType
checkedboolean): voiddefaultChecked?booleanrequired?booleanAttributeType
SwitchThumb
span
PropType
checkedboolean): voiddefaultChecked?booleanrequired?booleanAttributeType