Specification
- Catalogue
- No. 62 of 110
- Section
- Buttons and toggles
- Interaction
- Press
- Element
- Toggle
- Preview
- Live component
- Imports
- react 19.3.1
- Added
Notes
A switch whose thumb stretches toward its destination while it is pressed, then springs across when released. The stretch is a width change on :active; for a switch that is already on, the thumb also shifts left so it grows inward.
The travel uses an overshooting curve, so the thumb lands with a small bounce. The track colour changes on its own shorter transition, which keeps the two from feeling locked together.
Each switch is a button with role="switch" and aria-checked, labelled by the row text.
Code
React and plain CSS"use client";
import { useEffect, useState } from "react";
import type { LivePreviewProps } from "@/components/live/types";
import styles from "./toggle-switch.module.css";
const ROWS = [
{ id: "digest", label: "Email digest", hint: "A summary every Monday" },
{ id: "push", label: "Push alerts", hint: "Mentions and replies" },
{ id: "sound", label: "Sounds", hint: "Play a sound on new messages" },
];
const START = [true, false, true];
export default function ToggleSwitch({ active, context }: LivePreviewProps) {
const [values, setValues] = useState(START);
const [step, setStep] = useState(0);
const demo = active && context === "card";
// Each time the demo starts, it starts from the first step.
const [demoRunning, setDemoRunning] = useState(demo);
if (demoRunning !== demo) {
setDemoRunning(demo);
setStep(0);
}
useEffect(() => {
if (!demo) return;
const id = window.setInterval(() => setStep((s) => s + 1), 700);
return () => window.clearInterval(id);
}, [demo]);
// Demo: flips one row per step, top to bottom, so after six steps every row is back where it began.
const shown = context === "card" ? START.map((v, i) => (Math.floor((step + ROWS.length - 1 - i) / ROWS.length) % 2 === 1 ? !v : v)) : values;
return (
<ul className={styles.root}>
{ROWS.map((row, i) => {
const on = shown[i] ?? false;
return (
<li key={row.id} className={styles.row}>
<span className={styles.text}>
<span id={`switch-${row.id}`}>{row.label}</span>
<span className={styles.hint}>{row.hint}</span>
</span>
<button
type="button"
role="switch"
aria-checked={on}
aria-labelledby={`switch-${row.id}`}
tabIndex={context === "card" ? -1 : 0}
className={styles.switch}
onClick={() => setValues((list) => list.map((v, j) => (j === i ? !v : v)))}
>
<span className={styles.thumb} />
</button>
</li>
);
})}
</ul>
);
}