The Switch component is used to toggle between on/off states.
export const Example = () => {
return <Switch defaultChecked />;
};
If you haven't included Piksel UI in your project, include it first. You can check the installation page.
Copy the following source code and add it to your project.
"use client";
import React, { ComponentPropsWithRef, forwardRef } from "react";
import { tv, VariantProps } from "tailwind-variants";
import * as SwitchPrimitive from "@radix-ui/react-switch";
export const switchDisplayName = "Switch";
export type SwitchProps = ComponentPropsWithRef<typeof SwitchPrimitive.Root> &
VariantProps<typeof switchStyles>;
/**
* @name Switch
* @description The Switch component is used to toggle between on/off states.
*/
export const Switch = forwardRef<HTMLButtonElement, SwitchProps>(
(props, ref) => {
const { color, size, className, ...rest } = props;
const { root, thumb } = switchStyles({
color,
size,
});
return (
<SwitchPrimitive.Root className={root()} {...rest} ref={ref}>
<SwitchPrimitive.Thumb className={thumb()} />
</SwitchPrimitive.Root>
);
}
);
Switch.displayName = switchDisplayName;
export const switchStyles = tv({
slots: {
root: "relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-zinc-900 data-[state=unchecked]:bg-zinc-200",
thumb:
"pointer-events-none block h-5 w-5 rounded-full bg-white shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0",
},
variants: {
color: {
blue: {
root: "data-[state=checked]:bg-blue-600",
},
red: {
root: "data-[state=checked]:bg-red-600",
},
indigo: {
root: "data-[state=checked]:bg-indigo-600",
},
green: {
root: "data-[state=checked]:bg-green-600",
},
yellow: {
root: "data-[state=checked]:bg-yellow-600",
},
zinc: {
root: "data-[state=checked]:bg-zinc-600",
},
white: {
root: "data-[state=checked]:bg-white",
},
black: {
root: "data-[state=checked]:bg-black",
},
},
size: {
sm: {
root: "h-5 w-9",
thumb: "h-4 w-4 data-[state=checked]:translate-x-4",
},
md: {
root: "h-6 w-11",
thumb: "h-5 w-5 data-[state=checked]:translate-x-5",
},
lg: {
root: "h-7 w-12",
thumb: "h-6 w-6 data-[state=checked]:translate-x-5",
},
},
},
defaultVariants: {
color: "black",
size: "md",
},
});
The Switch component has the following props.
| Prop | Type | Default | Description |
|---|---|---|---|
color | 'blue' | 'red' | 'indigo' | 'green' | 'yellow' | 'zinc' | 'white' | 'black' | 'black' | The color of the switch. |
size | 'sm' | 'md' | 'lg' | 'md' | The size of the switch. |