Components
Switch

Switch

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

How it works

Install the following dependencies:

pnpm add @radix-ui/react-switch tailwind-merge clsx

Create a new file at lib/utils.ts and add the provided code.

import clsx, { ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
 
export function cn(...inputs: ClassValue[]) {
    return twMerge(clsx(inputs));
}

Create a file at components/ui/switch.tsx and paste the given code.

switch.tsx

"use client";
 
import * as SwitchPrimitives from "@radix-ui/react-switch";
import * as React from "react";
 
import { cn } from "@/lib/utils";
 
const Switch = React.forwardRef<
    React.ComponentRef<typeof SwitchPrimitives.Root>,
    React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
>(({ className, ...props }, ref) => (
    <SwitchPrimitives.Root
        className={cn(
            "peer inline-flex h-6 w-10 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent outline-offset-2 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring/70 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
            className,
        )}
        {...props}
        ref={ref}
    >
        <SwitchPrimitives.Thumb
            className={cn(
                "pointer-events-none block size-5 rounded-full bg-background shadow-sm shadow-black/5 ring-0 transition-transform duration-300 [transition-timing-function:cubic-bezier(0.16,1,0.3,1)] data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0 rtl:data-[state=checked]:-translate-x-4",
            )}
        />
    </SwitchPrimitives.Root>
));
Switch.displayName = SwitchPrimitives.Root.displayName;
 
export { Switch };

Import and use the switch component in your application.

import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
 
export default function SwitchDemo() {
    return (
        <div className="inline-flex items-center gap-2">
            <Switch id="switch-01" />
            <Label htmlFor="switch-01" className="sr-only">
                Simple switch
            </Label>
        </div>
    );
}

Examples

Default

Colored switch

Switch w/ icon

Switch w/ text

Sliding switch