# Spring Toggle

> A switch with a little squish in its step.

- Category: Buttons
- Tier: Free (MIT)
- Page: https://bowls.dev/components/spring-toggle
- Requires: React 18+, Tailwind CSS 4, motion

## Install

Copy the source below into `components/bowls/spring-toggle.tsx`, then install its dependencies:

```bash
npm i motion
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `label` | `string` | — | Accessible name for the switch. |
| `checked` | `boolean` | — | Controlled state. |
| `defaultChecked` | `boolean` | `false` | Initial state when uncontrolled. |
| `onCheckedChange` | `(checked: boolean) => void` | — | Called on every change. |
| `size` | `"sm" \| "md" \| "lg"` | `"md"` | Switch size. |

## Usage

```tsx
"use client";

import { SpringToggle } from "@/components/bowls/spring-toggle";

export default function Demo() {
  return (
    <div className="flex h-full w-full items-center justify-center gap-5">
      <SpringToggle label="Notifications" size="lg" defaultChecked />
      <SpringToggle label="Sounds" size="lg" />
      <SpringToggle label="Compact mode" size="md" defaultChecked />
    </div>
  );
}
```

## Source

`components/bowls/spring-toggle.tsx`

```tsx
"use client";

import { motion } from "motion/react";
import { useState } from "react";

export type SpringToggleProps = {
  checked?: boolean;
  defaultChecked?: boolean;
  onCheckedChange?: (checked: boolean) => void;
  /** Accessible name. Shown visually only if you render it yourself. */
  label: string;
  size?: "sm" | "md" | "lg";
  disabled?: boolean;
};

const SIZES = { sm: { w: 44, h: 26 }, md: { w: 64, h: 36 }, lg: { w: 84, h: 46 } };

export function SpringToggle({ checked, defaultChecked = false, onCheckedChange, label, size = "md", disabled }: SpringToggleProps) {
  const [inner, setInner] = useState(defaultChecked);
  const on = checked ?? inner;
  const { w, h } = SIZES[size];
  const pad = Math.round(h * 0.12);
  const knob = h - pad * 2;

  const toggle = () => {
    const next = !on;
    if (checked === undefined) setInner(next);
    onCheckedChange?.(next);
  };

  return (
    <button
      type="button"
      role="switch"
      aria-checked={on}
      aria-label={label}
      disabled={disabled}
      onClick={toggle}
      style={{ width: w, height: h, padding: pad }}
      className={`flex shrink-0 rounded-full transition-colors duration-300 disabled:opacity-40 ${
        on ? "justify-end bg-[#0a0a0a] dark:bg-[#f5f5f5]" : "justify-start bg-transparent shadow-[inset_0_0_0_2px_#0a0a0a] dark:shadow-[inset_0_0_0_2px_#f5f5f5]"
      }`}
    >
      <motion.span
        layout
        transition={{ type: "spring", stiffness: 520, damping: 26 }}
        whileTap={{ width: knob * 1.35 }}
        style={{ width: knob, height: knob }}
        className={`block rounded-full ${on ? "bg-white dark:bg-black" : "bg-[#0a0a0a] dark:bg-[#f5f5f5]"}`}
      />
    </button>
  );
}
```
