# Text Swap

> Animated text change for React and shadcn: a label or value swaps with a lift and blur while the width springs to fit.

Change a label, status or short value with y + blur, and spring the width to fit, so neighbours glide instead of jumping. Direction-aware for counts and steps.

Also known as a text morph.

- Tier: Free (MIT)
- Interaction: Press
- Page: https://eased.dev/components/text-swap
- Registry: https://eased.dev/r/text-swap.json

## Install

```bash
npx shadcn add https://eased.dev/r/text-swap.json
```

Changes a label, status or short value in place: the old text lifts and blurs out, the new text rises and sharpens, and the box springs to the new width so its neighbours glide instead of jumping.

## When to use

- A status that moves on: an order going from Packed to Shipped to Out for delivery.
- A button or link label that answers an action: Copy link to Copied, Save to Saved.
- A price, period or short value that changes with a setting, such as Monthly and Yearly pricing.
- Step labels and counts, where `direction` shows whether you went forward or back.

## When not to use

- Numbers that change often or by small steps, such as a counter or a balance: use [Number Roll](/components/number-roll), which turns each digit.
- Paragraphs or text that wraps: Text Swap never wraps, and is for one line.
- Swapping a whole region of content: use [Tabs](/components/tabs) or render the new content directly.

## Usage

```tsx order-status.tsx
import { TextSwap } from "@/components/eased/text-swap/text-swap";

export function OrderStatus({ status }: { status: string }) {
  return (
    <p aria-live="polite">
      Your order is <TextSwap>{status}</TextSwap>
    </p>
  );
}
```

## Examples

### Elements, with a swap key

When the children are elements, such as an icon and a label, pass `swapKey` so it knows when the content is new.

```tsx
<button onClick={copy}>
  <TextSwap swapKey={copied ? "copied" : "copy"}>
    {copied ? <><CheckIcon /> Copied</> : "Copy link"}
  </TextSwap>
</button>
```

### Direction

Pass `direction={-1}` for going back, or for a value going down, so the text travels the other way.

```tsx
<TextSwap direction={plan === "yearly" ? 1 : -1}>{plan === "yearly" ? "$96" : "$10"}</TextSwap>
```

## API reference

### TextSwap

| Prop | Type | Default | Description |
|---|---|---|---|
| `children` | `ReactNode` | | The text, or an icon and text, to show. Strings and numbers key themselves. |
| `swapKey` | `string \| number` | `children` | What counts as new content. Pass it when `children` are elements. |
| `direction` | `1 \| -1` | `1` | `1`: the new text rises from below and the old leaves upward. `-1` reverses it. |
| `animateWidth` | `boolean` | `true` | Spring the box's width to fit the new text. |
| `initial` | `boolean` | `false` | Animate the first render too. |

Every other `<span>` prop passes through to the outer span, including `className` and `style`.

## Accessibility

- The outgoing copy is `aria-hidden` while it leaves, so screen readers only ever find the current text.
- Text Swap does not announce changes itself. Put `aria-live="polite"` on a parent when the change should be read out, such as a status.

## Motion

The outgoing text lifts 3px and blurs out in 100ms; the incoming text rises from 4px below on the snappy spring while its opacity and 4px blur clear over 150ms, on their own clock so the blur never overshoots. With `direction={-1}` both travel the other way. The box's width springs to the new text on the smooth spring, and a swap that interrupts another continues from the current width. Reduced motion is a 100ms cross-fade and the width changes at once.

## Notes for AI

Use TextSwap around any short label or value that changes in response to state: button labels, statuses, prices. Strings key themselves; pass `swapKey` when the children are elements, and `direction={-1}` for back or down.

Do not use it for text that wraps or for numbers that tick, and do not wrap it in your own AnimatePresence or width transition: it already handles both. Eased's Button already swaps string labels (and element labels given `swapKey`) with the same engine, so pass the label to Button directly rather than wrapping it in TextSwap.

## Related

- [Number Roll](/components/number-roll): digits that roll to a new value.
- [Button](/components/button): its label swaps with the same motion.

## Example

`components/eased/text-swap/text-swap-demo.tsx`

```tsx
"use client";

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

const STEPS = [
  { label: "Order placed", detail: "Mon 14 Oct, 09:12" },
  { label: "Packed", detail: "Mon 14 Oct, 16:40" },
  { label: "Shipped from Leeds", detail: "Tue 15 Oct, 07:05" },
  { label: "Out for delivery", detail: "Wed 16 Oct, 08:31" },
  { label: "Delivered", detail: "Wed 16 Oct, 13:58" },
];

const PLANS = {
  monthly: { price: "$12", period: "per seat / month", note: "Billed monthly" },
  yearly: { price: "$120", period: "per seat / year", note: "Billed yearly, 2 months free" },
} as const;

export function TextSwapDemo() {
  const [step, setStep] = useState(2);
  const [direction, setDirection] = useState<1 | -1>(1);
  const [plan, setPlan] = useState<keyof typeof PLANS>("monthly");
  const [copied, setCopied] = useState(false);
  const timer = useRef(0);
  useEffect(() => () => clearTimeout(timer.current), []);

  const go = (to: number) => {
    setDirection(to > step ? 1 : -1);
    setStep(to);
  };

  const copy = () => {
    void navigator.clipboard?.writeText("https://acme.co/invite/7f3k9q").catch(() => {});
    setCopied(true);
    clearTimeout(timer.current);
    timer.current = window.setTimeout(() => setCopied(false), 1400);
  };

  const p = PLANS[plan];

  return (
    <DemoFrame title="Text Swap">
      <div className="flex min-h-0 flex-1 flex-col divide-y divide-line-subtle">
        <section className="flex flex-col gap-3 p-4" aria-label="Order status">
          <div className="flex items-start justify-between gap-3">
            <div className="min-w-0">
              <p className="text-ui-sm text-text-muted">Order #4182</p>
              <p className="text-ui font-medium text-text" aria-live="polite">
                <TextSwap direction={direction}>{STEPS[step].label}</TextSwap>
              </p>
              <p className="text-ui-sm text-text-muted tabular-nums">
                <TextSwap direction={direction}>{STEPS[step].detail}</TextSwap>
              </p>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <ol className="flex flex-1 gap-1" aria-hidden>
              {STEPS.map((s, i) => (
                <li
                  key={s.label}
                  className={`h-1 flex-1 rounded-pill transition-colors duration-200 ease-standard ${
                    i <= step ? "bg-text" : "bg-surface-active"
                  }`}
                />
              ))}
            </ol>
            <div className="flex shrink-0 gap-1">
              <Button variant="ghost" size="sm" onClick={() => go(step - 1)} disabled={step === 0}>
                Back
              </Button>
              <Button size="sm" onClick={() => go(step + 1)} disabled={step === STEPS.length - 1}>
                Next step
              </Button>
            </div>
          </div>
        </section>

        <section className="flex flex-col gap-3 p-4" aria-label="Pricing">
          <div className="flex items-center justify-between gap-3">
            <p className="text-ui font-medium text-text">Team plan</p>
            <Segmented
              aria-label="Billing period"
              size="sm"
              value={plan}
              onValueChange={setPlan}
              options={[
                { value: "monthly", label: "Monthly" },
                { value: "yearly", label: "Yearly" },
              ]}
            />
          </div>
          <div className="flex items-baseline gap-1.5">
            <span className="text-3xl font-semibold text-text tabular-nums">
              <TextSwap direction={plan === "yearly" ? 1 : -1}>{p.price}</TextSwap>
            </span>
            <span className="text-ui-sm text-text-muted">
              <TextSwap>{p.period}</TextSwap>
            </span>
          </div>
          <p className="text-ui-sm text-text-secondary">
            <TextSwap>{p.note}</TextSwap>
          </p>
        </section>

        <section className="flex items-center justify-between gap-3 p-4" aria-label="Invite link">
          <div className="min-w-0">
            <p className="text-ui font-medium text-text">Invite link</p>
            <p className="truncate font-mono text-ui-sm text-text-muted">acme.co/invite/7f3k9q</p>
          </div>
          <Button size="sm" onClick={copy} swapKey={copied ? "copied" : "copy"}>
            {copied ? (
              <>
                <svg viewBox="0 0 16 16" fill="none" aria-hidden className="size-4">
                  <path d="m3.75 8.5 2.75 2.75 5.75-6.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
                Copied
              </>
            ) : (
              "Copy link"
            )}
          </Button>
          <span role="status" className="sr-only">
            {copied ? "Link copied" : ""}
          </span>
        </section>
      </div>
    </DemoFrame>
  );
}
```
