Switch
A flat on/off switch, purple when on.
Install
$ npx shadcn@latest add @nudgekit/switchOr with no config: npx shadcn@latest add https://ui.nudgekit.app/r/switch.json
Usage
usage.tsx
import { Switch } from "@/components/ui/switch"
<label className="flex items-center gap-3">
<Switch checked={blockAds} onCheckedChange={setBlockAds} /> Block ads
</label>Do
- Use for settings that apply right away.
- Always pair it with a visible label.
Don't
- Use it in a form that needs a Save button; use a checkbox.
Code
What the CLI writes into your project. It is yours to change.
components/ui/switch.tsx
"use client";
import * as React from "react";
import { cn } from "@/lib/utils";
export interface SwitchProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, "onChange"> {
checked?: boolean;
defaultChecked?: boolean;
onCheckedChange?: (checked: boolean) => void;
}
/** A flat on/off switch. Brand purple when on, line grey when off. */
function Switch({ checked, defaultChecked = false, onCheckedChange, className, ...props }: SwitchProps) {
const [inner, setInner] = React.useState(defaultChecked);
const on = checked ?? inner;
return (
<button
type="button"
role="switch"
aria-checked={on}
data-slot="switch"
data-state={on ? "checked" : "unchecked"}
onClick={() => {
if (checked === undefined) setInner(!on);
onCheckedChange?.(!on);
}}
className={cn(
"relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full transition-colors duration-150",
"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:cursor-not-allowed disabled:opacity-50",
on ? "bg-brand" : "bg-line-strong",
className,
)}
{...props}
>
<span
aria-hidden
className={cn(
"inline-block size-4 rounded-full bg-white transition-transform duration-150 motion-reduce:transition-none",
on ? "translate-x-[18px]" : "translate-x-0.5",
)}
/>
</button>
);
}
export { Switch };