# Text Morph

> Shared-layout character morphing between two strings — individual letters animate to their new positions with spring physics.

Docs: https://ui.cnippet.dev/motion/text-animations/text-morph

```tsx
"use client";

import { useState } from "react";
import { TextMorph } from "@/registry/default/motion/text-morph";

const words = ["Innovate", "Collaborate", "Accelerate", "Automate"];

export default function TextMorphCycler() {
  const [index, setIndex] = useState(0);

  return (
    <div className="flex min-h-50 flex-col items-center justify-center gap-6 px-6">
      <h2 className="text-center font-bold text-4xl text-foreground tracking-tight sm:text-5xl">
        <TextMorph>{words[index] ?? words[0] ?? ""}</TextMorph>
      </h2>
      <div className="flex gap-2">
        {words.map((word, i) => (
          <button
            className={`rounded-md px-3 py-1 font-medium text-sm transition-colors ${
              i === index
                ? "bg-foreground text-background"
                : "bg-accent text-muted-foreground hover:text-foreground"
            }`}
            key={word}
            onClick={() => setIndex(i)}
            type="button"
          >
            {word}
          </button>
        ))}
      </div>
    </div>
  );
}
```

## Installation

**CLI**

```bash
npx shadcn@latest add @cnippet/text-morph
```

**Manual**

1. Install the following dependencies:

```bash
npm install motion
```

2. Copy and paste the following code into your project.

`components/motion/text-morph.tsx`

```tsx
"use client";

import {
  AnimatePresence,
  motion,
  type Transition,
  useReducedMotion,
  type Variants,
} from "motion/react";
import { useId, useMemo } from "react";
import { cn } from "@/lib/utils";

export type TextMorphProps = {
  children: string;
  as?: React.ElementType;
  className?: string;
  style?: React.CSSProperties;
  variants?: Variants;
  transition?: Transition;
};

const defaultVariants: Variants = {
  animate: { opacity: 1 },
  exit: { opacity: 0 },
  initial: { opacity: 0 },
};

const defaultTransition: Transition = {
  damping: 18,
  mass: 0.3,
  stiffness: 280,
  type: "spring",
};

export function TextMorph({
  children,
  as: Component = "p",
  className,
  style,
  variants,
  transition,
}: TextMorphProps) {
  const reduceMotion = useReducedMotion();
  const uniqueId = useId();

  const characters = useMemo(() => {
    const charCounts: Record<string, number> = {};
    return children.split("").map((char) => {
      const key = char.toLowerCase();
      charCounts[key] = (charCounts[key] || 0) + 1;
      return {
        id: `${uniqueId}-${key}${charCounts[key]}`,
        label: char === " " ? " " : char,
      };
    });
  }, [children, uniqueId]);

  return (
    <Component aria-label={children} className={cn(className)} style={style}>
      <AnimatePresence initial={false} mode="popLayout">
        {characters.map((character) => (
          <motion.span
            animate="animate"
            aria-hidden="true"
            className="inline-block"
            exit="exit"
            initial="initial"
            key={character.id}
            layoutId={character.id}
            transition={
              reduceMotion ? { duration: 0 } : (transition ?? defaultTransition)
            }
            variants={variants ?? defaultVariants}
          >
            {character.label}
          </motion.span>
        ))}
      </AnimatePresence>
    </Component>
  );
}
```

3. Update the import paths to match your project setup.

## Usage

```tsx
import { TextMorph } from "@/components/motion/text-morph";
```

```tsx
<TextMorph>{currentWord}</TextMorph>
```

## Anatomy

```tsx
<TextMorph>{currentWord}</TextMorph> {/* <p> whose letters morph when the text changes */}
```

## Good to know

- It animates when `children` changes. Pass a string from state and update it.
- Letters shared between the old and new text move into place; the others fade out and in.
- Screen readers get the current text through `aria-label`; the animated letters are hidden from them.
- When the user has turned on reduced motion, the new text replaces the old one instantly, with no morph.

## Props

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `children` | `string` | — | The string to display; change this prop to trigger morphing |
| `as` | `React.ElementType` | `"p"` | HTML tag for the container |
| `transition` | `Transition` | spring (stiffness 280) | Motion transition for character movement |
| `variants` | `Variants` | opacity fade | Custom enter/exit variants per character |
| `className` | `string` | — | Class applied to the container |
| `style` | `React.CSSProperties` | — | Inline style for the container |

## Examples

### Word Cycler

A button group selects the active word and passes it as `children`. Characters shared between words animate smoothly to their new positions.

```tsx
"use client";

import { useState } from "react";
import { TextMorph } from "@/registry/default/motion/text-morph";

const words = ["Innovate", "Collaborate", "Accelerate", "Automate"];

export default function TextMorphCycler() {
  const [index, setIndex] = useState(0);

  return (
    <div className="flex min-h-50 flex-col items-center justify-center gap-6 px-6">
      <h2 className="text-center font-bold text-4xl text-foreground tracking-tight sm:text-5xl">
        <TextMorph>{words[index] ?? words[0] ?? ""}</TextMorph>
      </h2>
      <div className="flex gap-2">
        {words.map((word, i) => (
          <button
            className={`rounded-md px-3 py-1 font-medium text-sm transition-colors ${
              i === index
                ? "bg-foreground text-background"
                : "bg-accent text-muted-foreground hover:text-foreground"
            }`}
            key={word}
            onClick={() => setIndex(i)}
            type="button"
          >
            {word}
          </button>
        ))}
      </div>
    </div>
  );
}
```

### Auto-Cycling Plan Name

An interval drives the `children` prop through an array. The tighter spring `transition` creates a snappier feel suitable for compact UI.

```tsx
"use client";

import { useEffect, useState } from "react";
import { TextMorph } from "@/registry/default/motion/text-morph";

const plans = ["Starter", "Pro", "Enterprise"];

export default function TextMorphPricing() {
  const [index, setIndex] = useState(0);

  useEffect(() => {
    const id = setInterval(() => setIndex((i) => (i + 1) % plans.length), 2200);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="flex min-h-50 items-center justify-center px-6">
      <div className="w-full max-w-xs rounded-xl border border-border bg-card p-6 text-center">
        <p className="mb-1 font-medium text-muted-foreground text-xs uppercase tracking-widest">
          Current plan
        </p>
        <TextMorph
          as="h3"
          className="font-bold text-3xl text-foreground"
          transition={{
            damping: 20,
            mass: 0.25,
            stiffness: 320,
            type: "spring",
          }}
        >
          {plans[index] ?? plans[0] ?? ""}
        </TextMorph>
        <p className="mt-3 text-muted-foreground text-sm">
          Upgrade or downgrade at any time.
        </p>
      </div>
    </div>
  );
}
```

### Morphing Placeholder

The placeholder string cycles as the user types, morphing character-by-character. Controlled by `query.length % suggestions.length` so each keystroke advances the suggestion.

```tsx
"use client";

import { useState } from "react";
import { TextMorph } from "@/registry/default/motion/text-morph";

const suggestions = ["Search docs", "Search components", "Search examples"];

export default function TextMorphSearch() {
  const [query, setQuery] = useState("");
  const placeholder =
    suggestions[query.length % suggestions.length] ?? suggestions[0];

  return (
    <div className="flex min-h-50 flex-col items-center justify-center gap-4 px-6">
      <div className="relative w-full max-w-md">
        <div className="pointer-events-none absolute inset-y-0 left-3.5 flex items-center text-muted-foreground">
          <svg
            className="h-4 w-4"
            fill="none"
            stroke="currentColor"
            strokeWidth={2}
            viewBox="0 0 24 24"
          >
            <circle cx="11" cy="11" r="8" />
            <path d="m21 21-4.35-4.35" />
          </svg>
        </div>
        <input
          className="h-10 w-full rounded-lg border border-border bg-background pr-4 pl-9 text-foreground text-sm outline-none placeholder:text-transparent focus:ring-2 focus:ring-ring"
          onChange={(e) => setQuery(e.target.value)}
          type="text"
          value={query}
        />
        {!query && (
          <div className="pointer-events-none absolute inset-y-0 left-9 flex items-center">
            <TextMorph className="text-muted-foreground text-sm">
              {placeholder ?? ""}
            </TextMorph>
          </div>
        )}
      </div>
      <p className="text-muted-foreground text-xs">
        Placeholder morphs as you type
      </p>
    </div>
  );
}
```
