Overview

A switch that feels physical. The thumb springs across, stretches toward where it's going while pressed, and can be dragged; letting go commits to whichever side it's nearer. A check draws itself in the thumb when on. loading puts a spinner in the thumb and holds input while you save, and description adds a line under the label. Space toggles it, and the arrow keys set a side directly.


Installation

Use the CLI to install the component automatically:

$ pnpm dlx shadcn@latest add https://ui.sanjid.in/r/toggle-switch.json

Install dependencies:

$ pnpm add motion

Add the utility function for class merging:

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

Copy the component code into your project:

components/ui/toggle-switch.tsx
tsx
"use client";
import React, { useCallback, useId, useRef, useState } from "react";import { AnimatePresence, motion, useReducedMotion } from "motion/react";import { cn } from "@/lib/utils";
export type ToggleSwitchProps = {  checked?: boolean;  defaultChecked?: boolean;  onCheckedChange?: (checked: boolean) => void;  label?: string;  /** Secondary line under the label. */  description?: string;  /** Shows a spinner in the thumb and blocks input, e.g. while saving. */  loading?: boolean;  size?: "sm" | "md" | "lg";  disabled?: boolean;  className?: string;  /** Accessible name when no visible `label` is given. */  "aria-label"?: string;};
const SIZES = {  sm: { w: 36, h: 20, thumb: 16 },  md: { w: 48, h: 28, thumb: 24 },  lg: { w: 60, h: 34, thumb: 30 },};const PAD = 2;const SPRING = { type: "spring" as const, stiffness: 700, damping: 38, mass: 0.7 };
export function ToggleSwitch({  checked: checkedProp,  defaultChecked = false,  onCheckedChange,  label,  description,  loading = false,  size = "md",  disabled,  className,  "aria-label": ariaLabel = "Toggle",}: ToggleSwitchProps) {  const reduce = !!useReducedMotion();  const id = useId();  const isControlled = checkedProp !== undefined;  const [uncontrolled, setUncontrolled] = useState(defaultChecked);  const checked = isControlled ? checkedProp : uncontrolled;  const [pressed, setPressed] = useState(false);  const [dragX, setDragX] = useState<number | null>(null);  const drag = useRef<{ x: number; moved: boolean } | null>(null);  const suppressClick = useRef(false);  const inert = disabled || loading;
  const { w, h, thumb } = SIZES[size];  const travel = w - thumb - PAD * 2;  // The thumb stretches while pressed, growing toward the side it will travel to.  const stretch = pressed && !reduce ? Math.round(thumb * 0.28) : 0;  const baseX = checked ? travel : 0;  const x = dragX ?? (checked ? baseX - stretch : baseX);
  const setChecked = useCallback(    (next: boolean) => {      if (!isControlled) setUncontrolled(next);      onCheckedChange?.(next);    },    [isControlled, onCheckedChange],  );
  const onPointerDown = (e: React.PointerEvent<HTMLButtonElement>) => {    if (inert || e.button !== 0) return;    setPressed(true);    drag.current = { x: e.clientX, moved: false };    try {      e.currentTarget.setPointerCapture(e.pointerId);    } catch {      /* Pointer may already be gone. */    }  };
  const onPointerMove = (e: React.PointerEvent<HTMLButtonElement>) => {    const d = drag.current;    if (!d) return;    const dx = e.clientX - d.x;    if (!d.moved && Math.abs(dx) < 3) return;    d.moved = true;    setDragX(Math.min(travel - stretch, Math.max(0, baseX - (checked ? stretch : 0) + dx)));  };
  const endDrag = (cancelled: boolean) => {    const d = drag.current;    drag.current = null;    setPressed(false);    if (d?.moved && dragX !== null && !cancelled) {      // A drag commits to whichever side the thumb is nearer; the click that      // follows pointerup must not toggle it again.      suppressClick.current = true;      const next = dragX + (thumb + stretch) / 2 > w / 2 - PAD;      if (next !== checked) setChecked(next);    }    setDragX(null);  };
  return (    <div className={cn("inline-flex items-start gap-3", inert && disabled && "opacity-50", className)}>      <motion.button        id={id}        type="button"        role="switch"        aria-checked={checked}        aria-busy={loading || undefined}        aria-labelledby={label ? `${id}-label` : undefined}        aria-describedby={description ? `${id}-desc` : undefined}        aria-label={label ? undefined : ariaLabel}        disabled={disabled}        onClick={() => {          if (suppressClick.current) {            suppressClick.current = false;            return;          }          if (!inert) setChecked(!checked);        }}        onPointerDown={onPointerDown}        onPointerMove={onPointerMove}        onPointerUp={() => endDrag(false)}        onPointerCancel={() => endDrag(true)}        onKeyDown={(e) => {          // Arrow keys set the side directly, like a physical switch.          if (inert) return;          if (e.key === "ArrowRight" && !checked) setChecked(true);          if (e.key === "ArrowLeft" && checked) setChecked(false);        }}        className={cn(          "relative shrink-0 touch-none rounded-full outline-none select-none",          "transition-[background-color,box-shadow] duration-300 ease-out",          "focus-visible:ring-2 focus-visible:ring-(--color-focus) focus-visible:ring-offset-2 focus-visible:ring-offset-(--color-paper)",          inert ? "cursor-not-allowed" : "cursor-pointer",          checked            ? "bg-(--color-ink) shadow-[inset_0_1px_2px_rgba(0,0,0,0.25)]"            : "bg-(--color-paper-2) shadow-[inset_0_0_0_1px_var(--color-rule),inset_0_1px_2px_rgba(0,0,0,0.06)]",        )}        style={{ width: w, height: h }}      >        <motion.span          aria-hidden          className="absolute flex items-center justify-center rounded-full bg-(--color-paper) shadow-[0_1px_1px_rgba(0,0,0,0.06),0_2px_6px_rgba(0,0,0,0.18)]"          style={{ top: PAD, left: PAD, height: thumb }}          initial={false}          animate={{ x, width: thumb + stretch }}          transition={dragX !== null || reduce ? { duration: 0 } : SPRING}        >          <AnimatePresence initial={false} mode="popLayout">            {loading ? (              <motion.svg                key="spin"                viewBox="0 0 16 16"                className="text-(--color-neutral)"                style={{ width: thumb * 0.55, height: thumb * 0.55 }}                initial={{ opacity: 0, scale: 0.5 }}                animate={{ opacity: 1, scale: 1, rotate: 360 }}                exit={{ opacity: 0, scale: 0.5 }}                transition={{ rotate: { repeat: Infinity, ease: "linear", duration: 0.8 }, default: { duration: 0.2 } }}              >                <circle cx="8" cy="8" r="6" fill="none" stroke="currentColor" strokeOpacity="0.25" strokeWidth="2.2" />                <path d="M14 8a6 6 0 0 0-6-6" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" />              </motion.svg>            ) : checked ? (              <motion.svg                key="on"                viewBox="0 0 16 16"                className="text-(--color-ink)"                style={{ width: thumb * 0.5, height: thumb * 0.5 }}                fill="none"                stroke="currentColor"                strokeWidth="2.6"                strokeLinecap="round"                strokeLinejoin="round"                initial={{ opacity: 0, scale: 0.5 }}                animate={{ opacity: 1, scale: 1 }}                exit={{ opacity: 0, scale: 0.5 }}                transition={{ duration: 0.18 }}              >                <motion.path                  d="M3.5 8.5l3 3 6-7"                  initial={{ pathLength: reduce ? 1 : 0 }}                  animate={{ pathLength: 1 }}                  transition={{ duration: 0.25, delay: 0.05 }}                />              </motion.svg>            ) : null}          </AnimatePresence>        </motion.span>      </motion.button>
      {label || description ? (        <div className={cn("flex min-w-0 flex-col", size === "sm" ? "pt-px" : size === "lg" ? "pt-1.5" : "pt-[3px]")}>          {label ? (            <label              htmlFor={id}              id={`${id}-label`}              className={cn("text-[14px] leading-snug font-medium text-(--color-ink)", !inert && "cursor-pointer")}            >              {label}            </label>          ) : null}          {description ? (            <span id={`${id}-desc`} className="mt-0.5 text-[12.5px] leading-snug text-(--color-neutral)">              {description}            </span>          ) : null}        </div>      ) : null}    </div>  );}

Adjust import paths according to your folder structure.


Basic Usage

tsx
import { ToggleSwitch } from "@/components/ui/toggle-switch";
<ToggleSwitch  label="Mention alerts"  description="When someone @mentions you"  checked={mentions}  onCheckedChange={setMentions}/>
// Saving to a server<ToggleSwitch  label="Sync to calendar"  checked={sync}  loading={saving}  onCheckedChange={async (next) => {    setSaving(true);    await save(next);    setSync(next);    setSaving(false);  }}/>

Props

PropTypeRequiredDefaultDescription
checked / defaultCheckedbooleanNo—Controlled or initial state.
onCheckedChange(checked: boolean) => voidNo—Fires on click, drag, Space or arrow keys.
label / descriptionstringNo—Visible label (click it to toggle) and a secondary line, both linked for screen readers.
loadingbooleanNofalseSpinner in the thumb; input is ignored until it clears.
size"sm" | "md" | "lg"No"md"Track of 36×20, 48×28 or 60×34 px.
disabledbooleanNo—Dims and disables the switch.
aria-label / classNamestringNo—Accessible name when there's no label, and wrapper classes.

Best Practices

  1. Use a switch for settings that apply immediately; use a checkbox inside forms that are submitted.
  2. With async saves, keep checked at the old value and set loading until the server answers, so the switch never shows a state that didn't save.
  3. Keep labels short and put the consequence in description.
  4. Reduced motion moves the thumb instantly without the stretch or the drawn check.