Text Morph
Text morph animation: cycle through words with a letter-level morph where shared letters glide into place and the rest blur away.
- Text Effects
- SaaS
- React only · 0 deps
- 1 file
Browser support · Evergreen browsers (individual translate property). Reduced motion: no auto-cycle, 120ms fades.
Install. One command, or copy the file.
$
npx shadcn@latest add https://freedesignmd.com/r/text-morph.json- Byte-identical to the preview
- No Tailwind or config needed
- SSR-safe · keyboard accessible
- Respects reduced motion & transparency
components/text/text-morph.tsx
1/**2 * TextMorph, cycles through words and morphs between them letter by letter.3 * Letters shared by both words glide to their new positions; the rest blur4 * and fade out or in. The slot width eases with the letters, so a centred5 * line stays centred instead of jumping.6 *7 * Props8 * - words: string[] Words or short phrases to cycle through.9 * - interval?: number ms each word is held. Default 2600.10 * - index?: number Controlled index (disables auto-cycling).11 * - paused?: boolean Pause auto-cycling (also paused off-screen and on reduced motion).12 * - onIndexChange?: (i) => void13 * - className / style Size it with font-size; the slot inherits typography.14 * CSS vars on root: --fd-tm-dur (default 560ms), --fd-tm-blur (default 8px).15 *16 * Accessibility: letters are aria-hidden; a visually hidden copy carries the17 * current word without a live region (no announcements every few seconds).18 * Give cycling heroes a pause control (WCAG 2.2.2), see the Demo.19 * Reduced motion: words swap with a 120ms cross-fade and don't auto-cycle.20 * Browser support: evergreen browsers (individual `translate` property:21 * Chrome 104, Safari 14.1, Firefox 72).22 */23import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";24import type { CSSProperties } from "react";25 26type Glyph = { id: number; ch: string; x: number; state: "in" | "stay" | "out" };27type Metrics = { xs: number[][]; widths: number[] };28 29export interface TextMorphProps {30 words: string[];31 interval?: number;32 index?: number;33 paused?: boolean;34 onIndexChange?: (i: number) => void;35 className?: string;36 style?: CSSProperties;37}38 39const useIso = typeof window === "undefined" ? useEffect : useLayoutEffect;40 41/** Pair each letter of `to` with an unused identical letter of `from`, preferring similar relative positions. */42function match(from: string, to: string) {43 const used = new Set<number>();44 const pairs: number[] = [];45 for (let j = 0; j < to.length; j++) {46 let best = -1;47 let bestD = Infinity;48 for (let i = 0; i < from.length; i++) {49 if (used.has(i) || from[i] !== to[j] || to[j] === " ") continue;50 const d = Math.abs(i / Math.max(1, from.length) - j / Math.max(1, to.length));51 if (d < bestD) {52 bestD = d;53 best = i;54 }55 }56 if (best >= 0) used.add(best);57 pairs.push(best);58 }59 return pairs;60}61 62export function TextMorph({ words, interval = 2600, index, paused, onIndexChange, className, style }: TextMorphProps) {63 const root = useRef<HTMLSpanElement>(null);64 const measurer = useRef<HTMLSpanElement>(null);65 const metrics = useRef<Metrics | null>(null);66 const [auto, setAuto] = useState(0);67 const cur = index ?? auto;68 const word = words[((cur % words.length) + words.length) % words.length] ?? "";69 const [glyphs, setGlyphs] = useState<Glyph[]>(() => Array.from(word).map((ch, i) => ({ id: i, ch, x: 0, state: "stay" as const })));70 const [width, setWidth] = useState<number | null>(null);71 const prev = useRef({ word, glyphs });72 const nextId = useRef(1000);73 const visible = useRef(true);74 const autoRef = useRef(0);75 const cbRef = useRef(onIndexChange);76 cbRef.current = onIndexChange;77 78 const measure = () => {79 const m = measurer.current;80 if (!m) return;81 const rows = Array.from(m.children) as HTMLElement[];82 metrics.current = {83 xs: rows.map((r) => Array.from(r.children).map((c) => (c as HTMLElement).offsetLeft)),84 widths: rows.map((r) => r.offsetWidth),85 };86 };87 88 // initial + resize measurement; place current glyphs without animating89 useIso(() => {90 const el = root.current;91 if (!el) return;92 const place = () => {93 measure();94 const wi = words.indexOf(prev.current.word);95 const mt = metrics.current;96 if (!mt || wi < 0) return;97 el.setAttribute("data-snap", "");98 const g = Array.from(prev.current.word).map((ch, i) => ({ id: nextId.current++, ch, x: mt.xs[wi][i] ?? 0, state: "stay" as const }));99 prev.current.glyphs = g;100 setGlyphs(g);101 setWidth(mt.widths[wi]);102 requestAnimationFrame(() => requestAnimationFrame(() => el.removeAttribute("data-snap")));103 };104 place();105 const ro = new ResizeObserver(place);106 if (measurer.current) ro.observe(measurer.current);107 document.fonts?.ready.then(place).catch(() => {});108 return () => ro.disconnect();109 // eslint-disable-next-line react-hooks/exhaustive-deps110 }, [words.join("|")]);111 112 // morph on word change113 useIso(() => {114 const from = prev.current;115 if (from.word === word) return;116 const mt = metrics.current;117 const wi = words.indexOf(word);118 if (!mt || wi < 0) return;119 const live = from.glyphs.filter((g) => g.state !== "out");120 const pairs = match(live.map((g) => g.ch).join(""), word);121 const taken = new Set<number>();122 const next: Glyph[] = Array.from(word).map((ch, j) => {123 const k = pairs[j];124 if (k >= 0) {125 taken.add(k);126 return { id: live[k].id, ch, x: mt.xs[wi][j], state: "stay" };127 }128 return { id: nextId.current++, ch, x: mt.xs[wi][j], state: "in" };129 });130 const leaving: Glyph[] = live.filter((_, k) => !taken.has(k)).map((g) => ({ ...g, state: "out" }));131 const all = [...next, ...leaving];132 prev.current = { word, glyphs: next };133 setGlyphs(all);134 setWidth(mt.widths[wi]);135 const t = window.setTimeout(() => setGlyphs((gs) => gs.filter((g) => g.state !== "out")), 640);136 return () => window.clearTimeout(t);137 // eslint-disable-next-line react-hooks/exhaustive-deps138 }, [word]);139 140 // auto-cycle (uncontrolled), paused off-screen / hidden / reduced motion141 useEffect(() => {142 if (index !== undefined || paused || words.length < 2) return;143 const reduced = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;144 if (reduced) return;145 const el = root.current;146 let io: IntersectionObserver | null = null;147 if (el && "IntersectionObserver" in window) {148 io = new IntersectionObserver((es) => (visible.current = es.some((e) => e.isIntersecting)));149 io.observe(el);150 }151 const id = window.setInterval(() => {152 if (!visible.current || document.hidden) return;153 autoRef.current = (autoRef.current + 1) % words.length;154 setAuto(autoRef.current);155 cbRef.current?.(autoRef.current);156 }, interval);157 return () => {158 window.clearInterval(id);159 io?.disconnect();160 };161 }, [index, paused, interval, words.length]);162 163 return (164 <span165 ref={root}166 className={`fd-tm${className ? " " + className : ""}`}167 data-ready={width == null ? undefined : ""}168 style={{ ...style, width: width == null ? undefined : `${width}px` }}169 >170 <style>{css}</style>171 <span className="fd-tm-sr">{word}</span>172 <span className="fd-tm-measure" ref={measurer} aria-hidden="true">173 {words.map((w, i) => (174 <span key={i} className="fd-tm-mrow">175 {Array.from(w).map((ch, j) => (176 <span key={j} className="fd-tm-mch">{ch}</span>177 ))}178 </span>179 ))}180 </span>181 <span className="fd-tm-ghost" aria-hidden="true">{word}</span>182 <span className="fd-tm-stage" aria-hidden="true">183 {glyphs.map((g) => (184 <span key={g.id} className="fd-tm-g" data-state={g.state} style={{ translate: `${g.x}px 0` }}>185 {g.ch === " " ? " " : g.ch}186 </span>187 ))}188 </span>189 </span>190 );191}192 193const css = `194.fd-tm,.fd-tm *,.fd-tm *::before,.fd-tm *::after{box-sizing:border-box}195.fd-tm{--fd-ease-out:cubic-bezier(.22,1,.36,1);--fd-ease-in-out:cubic-bezier(.65,0,.35,1);--fd-tm-dur:560ms;--fd-tm-blur:8px;196 position:relative;display:inline-block;vertical-align:baseline;margin:0;padding:0;white-space:nowrap;197 transition:width var(--fd-tm-dur) var(--fd-ease-in-out)}198.fd-tm[data-snap],.fd-tm[data-snap] *{transition:none!important;animation:none!important}199.fd-tm-sr{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap;border:0}200.fd-tm-measure{position:absolute;left:0;top:0;visibility:hidden;pointer-events:none;margin:0;padding:0;white-space:pre}201.fd-tm-mrow{position:absolute;left:0;top:0;display:inline-block;margin:0;padding:0;white-space:pre}202.fd-tm-mch{display:inline;margin:0;padding:0}203.fd-tm-ghost{display:inline-block;visibility:hidden;width:0;margin:0;padding:0;white-space:pre}204.fd-tm:not([data-ready]) .fd-tm-ghost{visibility:visible;width:auto}205.fd-tm:not([data-ready]) .fd-tm-stage{visibility:hidden}206.fd-tm-stage{position:absolute;left:0;top:0;bottom:0;display:block;margin:0;padding:0}207.fd-tm-g{position:absolute;left:0;top:0;display:inline-block;margin:0;padding:0;white-space:pre;will-change:translate,opacity,filter;208 transition:translate var(--fd-tm-dur) var(--fd-ease-in-out),opacity var(--fd-tm-dur) var(--fd-ease-out),filter var(--fd-tm-dur) var(--fd-ease-out)}209.fd-tm-g[data-state="in"]{animation:fd-tm-in var(--fd-tm-dur) var(--fd-ease-out) calc(var(--fd-tm-dur) * .28) both}210.fd-tm-g[data-state="out"]{animation:fd-tm-out calc(var(--fd-tm-dur) * .7) var(--fd-ease-out) both;pointer-events:none}211@keyframes fd-tm-in{from{opacity:0;filter:blur(var(--fd-tm-blur));transform:translate3d(0,.22em,0) scale(.92)}to{opacity:1;filter:blur(0);transform:none}}212@keyframes fd-tm-out{from{opacity:1;filter:blur(0);transform:none}to{opacity:0;filter:blur(var(--fd-tm-blur));transform:translate3d(0,-.18em,0) scale(.94)}}213@media (prefers-reduced-motion:reduce){214 .fd-tm,.fd-tm-g{transition:none}215 .fd-tm-g[data-state="in"]{animation:fd-tm-fade 120ms linear both}216 .fd-tm-g[data-state="out"]{animation:none;opacity:0}217}218@keyframes fd-tm-fade{from{opacity:0}to{opacity:1}}219`;220 221/* ───────────────────────────── demo ───────────────────────────── */222 223const WORDS = ["founders", "agents", "teams", "everyone"];224 225export function Demo() {226 const [paused, setPaused] = useState(false);227 const words = useMemo(() => WORDS, []);228 return (229 <div className="fd-tmd">230 <style>{demoCss}</style>231 <h2 className="fd-tmd-line">232 <span className="fd-tmd-pre">Built for</span>{" "}233 <TextMorph words={words} paused={paused} className="fd-tmd-word" />234 </h2>235 <button type="button" className="fd-tmd-btn" onClick={() => setPaused((p) => !p)} aria-pressed={paused}>236 {paused ? "Resume" : "Pause"}237 </button>238 </div>239 );240}241 242const demoCss = `243.fd-tmd,.fd-tmd *,.fd-tmd *::before,.fd-tmd *::after{box-sizing:border-box}244.fd-tmd{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:44px;min-height:100vh;width:100%;margin:0;padding:32px 20px;overflow:hidden;background:#f2f2f2;color:#1d1d1f;font:400 15px/1.4 ui-sans-serif,-apple-system,BlinkMacSystemFont,"SF Pro Text","Inter","Segoe UI",Roboto,sans-serif;letter-spacing:normal;-webkit-font-smoothing:antialiased}245.fd-tmd-line{margin:0;padding:0;max-width:100%;text-align:center;color:#1d1d1f;font:600 clamp(36px,8vw,88px)/1.1 "SF Pro Display",ui-sans-serif,-apple-system,"Inter Display","Inter",sans-serif;letter-spacing:-.045em}246.fd-tmd-pre{display:inline-block;margin:0;padding:0;color:#86868b}247.fd-tmd-word{color:#1d1d1f}248@media (max-width:640px){.fd-tmd-pre{display:block}}249.fd-tmd-btn{appearance:none;-webkit-appearance:none;margin:0;height:34px;padding:0 16px;border:0;border-radius:9999px;background:rgba(0,0,0,.06);color:#3c3c43;font:500 13px/1 ui-sans-serif,-apple-system,BlinkMacSystemFont,"SF Pro Text","Inter","Segoe UI",Roboto,sans-serif;letter-spacing:normal;cursor:pointer;transition:background-color 200ms}250.fd-tmd-btn:hover{background:rgba(0,0,0,.1)}251.fd-tmd-btn:focus-visible{outline:2px solid rgba(10,132,255,.8);outline-offset:2px}252`;More Text Effects. Same file contract.
Questions about Text Morph
Run npx shadcn@latest add https://freedesignmd.com/r/text-morph.json, or open the page and copy the file into your project. It has zero dependencies besides React. What you copy is the exact file that renders the live demo.
Text morph animation: cycle through words with a letter-level morph where shared letters glide into place and the rest blur away. It is a free, MIT-licensed React text effects component from the freedesignmd library.
Yes. It is free and MIT-licensed, use, modify and ship it in personal and commercial projects without attribution.
Evergreen browsers (individual translate property). Reduced motion: no auto-cycle, 120ms fades.
Yes. It is a plain React component with its own styles, so it runs in Next.js, Vite, Remix and Lovable projects, and it needs no Tailwind setup. It has zero dependencies besides React.


