# Button

> Animated button for React and shadcn: labels swap while the width springs, and the loading spinner keeps its width.

A Base UI button whose press scale depends on its width, whose label swaps with y + blur while the width springs, and whose loading spinner overlays the label so the width never changes. Popover triggers never scale.

- Tier: Free (MIT)
- Interaction: Press
- Page: https://eased.dev/components/button
- Installs: @base-ui/react, motion
- Registry: https://eased.dev/r/button.json

## Install

```bash
npx shadcn add https://eased.dev/r/button.json
```

A button on Base UI's Button whose press scale follows its width, whose label swaps with y + blur while the width springs, and whose loading state keeps its width.

## When to use

- Any action on the page: save, send, open, delete. One `primary` per region marks the main one.
- Labels that change after the action ("Save" → "Saved"): the swap and the width spring are built in.
- Async work: `loading` overlays Eased's Spinner without moving anything around it.
- Square icon actions in toolbars and rows, with `size="icon-sm"` and an `aria-label`.

## When not to use

- Navigation to another page: use a link (`<Link>`), or pass `render={<Link href="…" />}` so it still looks like a button.
- Choosing one of a few options: use [Segmented](/components/segmented) or [Toggle Group](/components/toggle-group).
- An action that needs a second chance: pair the button with [Undo Pill](/components/undo-pill) instead of a confirm step, unless it cannot be reversed.

## Usage

```tsx save-button.tsx
import { Button } from "@/components/eased/button/button";

export function SaveButton({ pending, saved, onSave }: { pending: boolean; saved: boolean; onSave: () => void }) {
  return (
    <Button variant="primary" loading={pending} onClick={onSave}>
      {saved ? "Saved" : "Save"}
    </Button>
  );
}
```

## Examples

### Icon button

Square, with a 44×44 tap target around the 32px visual. Name it with `aria-label`.

```tsx
<Button variant="ghost" size="icon-sm" aria-label="Copy link">
  <LinkIcon />
</Button>
```

### Popover trigger

Triggers that anchor a popup never scale, so the popup's origin stays put. Passing the button as `render` is enough: `aria-haspopup` turns the scale off.

```tsx
<Popover.Trigger render={<Button />}>Share</Popover.Trigger>
```

### Swapping element labels

String labels swap on their own. When `children` are elements, give each state a `swapKey`.

```tsx
<Button swapKey={copied ? "copied" : "copy"}>
  {copied ? <><CheckIcon /> Copied</> : <><CopyIcon /> Copy</>}
</Button>
```

## API reference

| Prop | Type | Default | Description |
|---|---|---|---|
| `variant` | `"primary" \| "secondary" \| "ghost" \| "danger" \| "danger-solid"` | `"secondary"` | One `primary` per region. `danger` is outlined; `danger-solid` is for the final confirm step only. |
| `size` | `"sm" \| "md" \| "lg" \| "icon-sm" \| "icon" \| "icon-lg"` | `"md"` | 32, 36 and 40px; icon sizes are square. |
| `loading` | `boolean` | `false` | Eased's `Spinner` over a transparent label: width kept, focus kept, clicks ignored, `aria-busy`. |
| `swapKey` | `string \| number` | | Swap the label when `children` are elements. String labels swap on their own. |
| `scaleOnPress` | `boolean` | `true` | Off automatically for `aria-haspopup` triggers. |
| `hitArea` | `boolean` | `true` for `icon-sm` | 44×44 tap target around a small button. Pass `false` when the button sits beside other targets (toolbars, rows), so the extended area does not cover them. |

Plus every Base UI Button prop (`disabled`, `focusableWhenDisabled`, `render` …). `type` defaults to `"button"`.

## Keyboard

| Key | Action |
|---|---|
| `Enter` / `Space` | Activates the button. Ignored while `loading`. |
| `Tab` | Moves focus to the button, including while `loading`, and while disabled with `focusableWhenDisabled`. |

## Accessibility

- A native `<button>` with `type="button"` unless you say otherwise; Base UI keeps `disabled` buttons focusable when asked, so a tooltip or reason can still be read.
- `loading` sets `aria-busy` and keeps the label in the accessible name, so the button never goes nameless while the spinner shows.
- Content inside a button is not announced when it changes. Announce "Saved" with your own `role="status"` region.
- Icon-only sizes need an `aria-label`; `icon-sm` gets a 44×44 hit area by default.

## Motion

The press scale follows the width: 0.96 for icon buttons, 0.97 for text buttons and 0.985 past 220px, pressed down in 100ms and released on the snappy spring. A label change swaps with y + blur (out 3px up, in from 4px below) while the width springs to fit. Loading keeps the width, so the button never jumps. Reduced motion keeps the colour changes and drops the scale and the swap travel.

## Notes for AI

Reach for Button for every in-page action, and set `variant="primary"` on only the main action in a region. For async work, pass `loading` rather than disabling the button or swapping in a spinner yourself; for a confirmed state, change the string child and let the swap run.

Do not wrap it in another pressable element, add your own `transition-*` or `active:scale-*` classes, or animate its width: the component already owns press, swap and width. Use `render={<Link />}` for navigation instead of nesting a link inside it.

## Related

- [Spinner](/components/spinner): the loading indicator Button overlays.
- [Undo Pill](/components/undo-pill): the undo window for destructive buttons.
- [Segmented](/components/segmented): when the choice is one of a few options, not an action.

## Example

`components/eased/button/button-demo.tsx`

```tsx
"use client";

import { useEffect, useRef, useState } from "react";
import { TextSwap } from "../_primitives/text-swap/text-swap";
import { DemoFrame } from "../lib/demo-frame";
import { Button } from "./button";

type Status = "draft" | "sent" | "void";
type Send = "idle" | "sending" | "sent";

const STATUS: Record<Status, { label: string; tone: string }> = {
  draft: { label: "Draft", tone: "bg-surface-hover text-text-secondary" },
  sent: { label: "Sent", tone: "bg-success-subtle text-success-text" },
  void: { label: "Void", tone: "bg-danger-subtle text-danger-text" },
};

const LINES = [
  { item: "Design system audit", qty: "1", amount: 2400 },
  { item: "Component build, 12 items", qty: "12", amount: 1560 },
  { item: "Motion review", qty: "4h", amount: 320 },
];

const money = new Intl.NumberFormat("en-IE", { style: "currency", currency: "EUR" });

export function ButtonDemo() {
  const [status, setStatus] = useState<Status>("draft");
  const [send, setSend] = useState<Send>("idle");
  const [downloading, setDownloading] = useState(false);
  const [confirming, setConfirming] = useState(false);
  const [announce, setAnnounce] = useState("");
  const timers = useRef<number[]>([]);

  const later = (fn: () => void, ms: number) => timers.current.push(window.setTimeout(fn, ms));
  useEffect(() => () => timers.current.forEach(clearTimeout), []);

  const sendInvoice = () => {
    setSend("sending");
    later(() => {
      setSend("sent");
      setStatus("sent");
      setAnnounce("Invoice sent to Northwind Traders");
      later(() => setSend("idle"), 1800);
    }, 1200);
  };

  const download = () => {
    setDownloading(true);
    later(() => setDownloading(false), 1100);
  };

  const voidInvoice = () => {
    if (!confirming) return setConfirming(true);
    setConfirming(false);
    setStatus("void");
    setAnnounce("Invoice voided");
  };

  const reset = () => {
    setStatus("draft");
    setSend("idle");
    setAnnounce("");
  };

  const total = LINES.reduce((sum, l) => sum + l.amount, 0);
  const voided = status === "void";

  return (
    <DemoFrame
      title={
        <span className="flex min-w-0 items-center gap-2">
          <span className="truncate">Invoice INV-2041</span>
          <span
            className={`inline-flex h-5 shrink-0 items-center rounded-control-xs px-1.5 text-ui-xs font-medium transition-colors duration-150 ease-standard ${STATUS[status].tone}`}
          >
            <TextSwap>{STATUS[status].label}</TextSwap>
          </span>
        </span>
      }
      actions={
        <div className="flex items-center gap-0.5">
          <Button variant="ghost" size="icon-sm" hitArea={false} aria-label="Copy invoice link">
            <svg viewBox="0 0 16 16" fill="none" aria-hidden>
              <path
                d="M6.75 9.25a2.5 2.5 0 0 0 3.54 0l2-2a2.5 2.5 0 0 0-3.54-3.54l-.5.5M9.25 6.75a2.5 2.5 0 0 0-3.54 0l-2 2a2.5 2.5 0 0 0 3.54 3.54l.5-.5"
                stroke="currentColor"
                strokeWidth="1.5"
                strokeLinecap="round"
              />
            </svg>
          </Button>
          <Button variant="ghost" size="icon-sm" hitArea={false} edge="end" aria-label="Reset demo" onClick={reset}>
            <svg viewBox="0 0 16 16" fill="none" aria-hidden>
              <path
                d="M3.25 8a4.75 4.75 0 1 0 1.4-3.36M3.25 2.75v2.5h2.5"
                stroke="currentColor"
                strokeWidth="1.5"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
          </Button>
        </div>
      }
    >
      <div className="flex min-h-0 flex-1 flex-col">
        <div className="flex flex-col gap-4 p-4">
          <div className="flex items-baseline justify-between gap-3">
            <div className="min-w-0">
              <p className="text-ui-sm text-text-muted">Billed to</p>
              <p className="truncate text-ui font-medium text-text">Northwind Traders</p>
            </div>
            <div className="shrink-0 text-right">
              <p className="text-ui-sm text-text-muted">Due 24 Oct</p>
              <p className={`text-ui font-medium tabular-nums ${voided ? "text-text-muted line-through" : "text-text"}`}>
                {money.format(total)}
              </p>
            </div>
          </div>

          <ul className="flex flex-col border-t border-line-subtle">
            {LINES.map((l) => (
              <li key={l.item} className="flex h-9 min-w-0 items-center gap-3 border-b border-line-subtle text-ui-sm">
                <span className="min-w-0 flex-1 truncate text-text-secondary">{l.item}</span>
                <span className="w-8 shrink-0 text-right text-text-muted tabular-nums">{l.qty}</span>
                <span className="w-20 shrink-0 text-right text-text tabular-nums">{money.format(l.amount)}</span>
              </li>
            ))}
          </ul>

          <Button
            variant="secondary"
            size="sm"
            className="self-start"
            loading={downloading}
            onClick={download}
          >
            <svg viewBox="0 0 16 16" fill="none" aria-hidden>
              <path
                d="M8 2.75v7m0 0L5.25 7M8 9.75 10.75 7M3.25 11.5v.75c0 .55.45 1 1 1h7.5c.55 0 1-.45 1-1v-.75"
                stroke="currentColor"
                strokeWidth="1.5"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
            Download PDF
          </Button>
        </div>

        <div className="mt-auto flex items-center gap-2 border-t border-line-subtle px-4 py-3">
          <Button
            variant={confirming ? "danger-solid" : "danger"}
            size="sm"
            disabled={voided}
            focusableWhenDisabled
            onClick={voidInvoice}
            onBlur={() => setConfirming(false)}
            onKeyDown={(e) => e.key === "Escape" && setConfirming(false)}
          >
            {confirming ? "Void invoice?" : voided ? "Voided" : "Void"}
          </Button>
          <div className="flex-1" />
          <Button
            variant="primary"
            size="sm"
            disabled={voided}
            loading={send === "sending"}
            onClick={sendInvoice}
            swapKey={send === "sent" ? "sent" : status === "sent" ? "resend" : "send"}
          >
            {send === "sent" ? (
              <>
                <svg viewBox="0 0 16 16" fill="none" aria-hidden>
                  <path d="m3.75 8.5 2.75 2.75 5.75-6.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
                Sent
              </>
            ) : status === "sent" ? (
              "Resend"
            ) : (
              "Send invoice"
            )}
          </Button>
        </div>
      </div>
      <span role="status" className="sr-only">
        {announce}
      </span>
    </DemoFrame>
  );
}
```
