Number 44: Button that shows its own progress
Specification
- Catalogue
- No. 44 of 110
- Section
- Buttons and toggles
- Interaction
- Press, Loading, Feedback
- Element
- Button
- Preview
- Live component
- Imports
- react 19.3.1
- Added
Notes
Press it and the button fills as its own progress bar, then becomes a tick.
The answer appears where the hand is, instead of a spinner somewhere else. It has a state for every moment: rest, pressed, busy, done and error.
Press 120ms to scale 0.98. Fill runs as progress, tick draws in 300ms. Error shakes once and says what to do.
Code
React and plain CSS"use client";
import { useEffect, useRef, useState } from "react";
import type { LivePreviewProps } from "@/components/live/types";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "./progress-button.css";
type State = "idle" | "busy" | "done" | "error";
function ActionButton({ label, busy, done, fails }: { label: string; busy: string; done: string; fails?: boolean }) {
const [state, setState] = useState<State>("idle");
const timers = useRef<number[]>([]);
useEffect(() => () => timers.current.forEach((t) => window.clearTimeout(t)), []);
const run = () => {
if (state === "busy" || state === "done") return;
setState("busy");
timers.current.push(
window.setTimeout(() => {
setState(fails ? "error" : "done");
if (!fails) timers.current.push(window.setTimeout(() => setState("idle"), 2200));
}, 1400),
);
};
const text = state === "busy" ? busy : state === "error" ? "Try again" : label;
return (
<div className="pb-wrap">
<button type="button" className="pb" data-state={state} aria-disabled={state === "busy" || undefined} aria-busy={state === "busy" || undefined} onClick={run}>
<span className="pb-fill" aria-hidden="true" />
<span className="pb-label">{text}</span>
<svg className="pb-tick" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M5 12.5l4.5 4.5L19 7.5" />
</svg>
</button>
<p className="pb-msg" role="status" data-tone={state === "error" ? "error" : undefined}>
{state === "done" ? done : state === "error" ? "Card declined. Nothing was charged." : ""}
</p>
</div>
);
}
function ProgressButtonDemo() {
return (
<div className="dm">
<div className="dm-actions">
<ActionButton label="Send enquiry" busy="Sending" done="Sent. We reply within a day." />
<ActionButton label="Pay now" busy="Paying" done="" fails />
</div>
<p className="dm-hint">The second one shows the error state</p>
</div>
);
}
// What a hovered card shows: the piece used the way a visitor would.
const TOUR: Tour = [{ click: ".pb", nth: 0, wait: 3200 }];
export default function ProgressButtonEntry(props: LivePreviewProps) {
return (
<PieceStage {...props} label="Button that shows its own progress" tour={TOUR}>
<ProgressButtonDemo />
</PieceStage>
);
}