Craft›Spring Switch

Spring Switch

An iOS-style switch with a spring thumb that stretches toward its destination while you hold it and springs across on release; real switch role, keyboard, haptic tick, on colour as a prop.

Copy a ready prompt for Claude Code, Codex or Cursor

Seen on

Original to Copia

Dependencies

reacttailwindcssmotion

Interaction type

springkeyboard

Install via CLI

pnpm dlx shadcn@latest add @copia/spring-switch

Without the namespace: npx shadcn@latest add https://copia-ui.vercel.app/r/spring-switch.json

How to use

demo.tsx
"use client"

import { useEffect, useState } from "react"
import { SpringSwitch, type SpringSwitchProps } from "./spring-switch"

const SETTINGS = ["Wi-Fi", "Bluetooth", "Airplane mode"]

/** A small settings list that flips itself until you touch it. */
export default function Demo({ onColor = "#34c759" }: Pick<SpringSwitchProps, "onColor">) {
  const [values, setValues] = useState([true, false, false])
  const [auto, setAuto] = useState(true)

  useEffect(() => {
    if (!auto || matchMedia("(prefers-reduced-motion: reduce)").matches) return
    let step = 0
    const id = setInterval(() => {
      const i = step++ % SETTINGS.length
      setValues((v) => v.map((x, j) => (j === i ? !x : x)))
    }, 700)
    return () => clearInterval(id)
  }, [auto])

  return (
    <div className="grid flex-1 place-items-center p-6" onPointerDown={() => setAuto(false)} onKeyDown={() => setAuto(false)}>
      <ul className="flex w-64 flex-col divide-y divide-border rounded-2xl bg-muted/50 px-4">
        {SETTINGS.map((name, i) => (
          <li key={name} className="flex items-center justify-between py-3 text-sm">
            <span>{name}</span>
            <SpringSwitch aria-label={name} checked={values[i]} onCheckedChange={(on) => setValues((v) => v.map((x, j) => (j === i ? on : x)))} onColor={onColor} />
          </li>
        ))}
      </ul>
    </div>
  )
}

Customization

Use the sliders button at the top right of the preview to tweak onColor live and copy the generated JSX.

Props

PropTypeDefaultDescription
checked / defaultChecked / onCheckedChangeboolean / boolean / (on) => void- / false / -Controlled or uncontrolled.
labelstring-Visible label beside the switch.
onColorstring"#34c759"Track colour when on.
disabledbooleanfalseDims it and ignores input.
hapticsbooleantrueVibrate briefly on toggle, where supported.

Attribution

Original component, Apple (Human Interface Guidelines: Toggles). Recreated by Copia.

Read how it was reverse engineered

Source code

spring-switch.tsx
"use client"

import { motion, useReducedMotion } from "motion/react"
import { useId, useState } from "react"
import { cn } from "@/lib/utils"

export type SpringSwitchProps = {
  checked?: boolean
  defaultChecked?: boolean
  onCheckedChange?: (checked: boolean) => void
  /** Visible label beside the switch. */
  label?: string
  /** Accessible name when there is no visible label. */
  "aria-label"?: string
  /** Track colour when on (Apple's green by default). */
  onColor?: string
  disabled?: boolean
  /** A short vibration on toggle, where supported. */
  haptics?: boolean
  className?: string
}

const THUMB = { type: "spring", stiffness: 520, damping: 34, mass: 0.7 } as const

/**
 * An iOS-style switch with a spring thumb. Press and hold and the thumb
 * stretches toward where it will go, like the real one; release and it
 * springs across.
 */
export function SpringSwitch({ checked, defaultChecked = false, onCheckedChange, label, "aria-label": ariaLabel, onColor = "#34c759", disabled = false, haptics = true, className }: SpringSwitchProps) {
  const [internal, setInternal] = useState(defaultChecked)
  const [pressed, setPressed] = useState(false)
  const on = checked ?? internal
  const reduced = useReducedMotion()
  const id = useId()

  const toggle = () => {
    if (disabled) return
    if (checked === undefined) setInternal(!on)
    onCheckedChange?.(!on)
    if (haptics) navigator.vibrate?.(4)
  }

  return (
    <span className={cn("inline-flex items-center gap-3", disabled && "opacity-50", className)}>
      <button
        id={id}
        type="button"
        role="switch"
        aria-checked={on}
        aria-label={label ? undefined : (ariaLabel ?? "Toggle")}
        disabled={disabled}
        onClick={toggle}
        onPointerDown={() => setPressed(true)}
        onPointerUp={() => setPressed(false)}
        onPointerLeave={() => setPressed(false)}
        onKeyDown={(e) => e.key === " " && setPressed(true)}
        onKeyUp={() => setPressed(false)}
        className={cn(
          "relative flex h-[31px] w-[51px] shrink-0 items-center rounded-full p-[2px] outline-none transition-colors duration-300 focus-visible:ring-2 focus-visible:ring-ring",
          on ? "justify-end" : "justify-start bg-muted-foreground/30",
        )}
        style={{ background: on ? onColor : undefined }}
      >
        {/* The thumb widens while pressed (toward its destination) and springs on release. */}
        <motion.span
          layout
          transition={reduced ? { duration: 0 } : THUMB}
          animate={{ width: pressed && !reduced ? 34 : 27 }}
          className="block h-[27px] rounded-full bg-white shadow-[0_3px_8px_rgb(0_0_0/0.15),0_1px_1px_rgb(0_0_0/0.16)]"
        />
      </button>
      {label && (
        <label htmlFor={id} className="cursor-pointer text-sm select-none">
          {label}
        </label>
      )}
    </span>
  )
}

Keep in mind

Most components here are recreations of the best interfaces out there. We don't claim to be the original creators: this is our attempt to reverse engineer, replicate and often add a few features. We credit everyone we can; if we missed someone, let us know.

Contact

Found a bug or a missing credit? Open an issue

License & usage

  • — Free to use and modify in personal and commercial projects (MIT).
  • — No attribution required, but a link back to Copia is appreciated.
  • — Demo images are not part of the license; replace them with your own.
PreviousSpine AccordionNext Arc Picker
  • Wi-Fi
  • Bluetooth
  • Airplane mode