Flip Words
A flip words animation for React and Tailwind CSS: one word in a sentence flips over in 3D to the next on a timer, its letters flipping up one after another while the width springs smoothly between words. It pauses on hover and focus, and every word stays available to screen readers and search engines.
- 3D rotateX flip
- Letter stagger
- Width spring
- Pauses on hover / focus
- prefers-reduced-motion
Build faster, calmer, accessible, delightful
interfaces with DuskUI
import { FlipWords } from "@/components/dusk/flip-words/flip-words";
export default function FlipWordsDemo() {
return (
<h2 className="text-center text-4xl font-bold tracking-tight sm:text-5xl">
Build{" "}
<FlipWords words={["faster", "calmer", "accessible", "delightful"]} className="text-white/60" />
<br />
interfaces with DuskUI
</h2>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/flip-words.json1. Install the dependencies.
npm install motion2. Copy the source into
components/dusk/flip-words/flip-words.tsx.flip-words.tsx "use client"; import * as React from "react"; import { AnimatePresence, animate, motion, useInView, useMotionValue, usePageInView, useReducedMotion, type AnimationPlaybackControls, type Variants, } from "motion/react"; import { cn } from "@/lib/utils"; type FlipWordsTag = "span" | "strong" | "em" | "p" | "div" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6"; export interface FlipWordsProps extends Omit<React.HTMLAttributes<HTMLElement>, "children"> { /** Words (or short phrases) to flip through. The first one is server-rendered. */ words: string[]; /** Milliseconds each word stays before flipping (minimum 1200). */ interval?: number; /** Element to render. `span` (default) sits inline in a sentence. */ as?: FlipWordsTag; /** Seconds between letters of the incoming word. */ letterStagger?: number; /** Pause while the pointer is over the word or focus is inside it. */ pauseOnHover?: boolean; /** Classes for each word, e.g. a color. */ wordClassName?: string; } /** User-perceived characters, so emoji and accented letters aren't split apart. */ function graphemes(text: string): string[] { if (typeof Intl !== "undefined" && "Segmenter" in Intl) { return Array.from(new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(text), (s) => s.segment); } return Array.from(text); } const PERSPECTIVE = 600; const letterVariants: Variants = { hidden: { opacity: 0, rotateX: -90, y: "0.3em", filter: "blur(4px)" }, visible: { opacity: 1, rotateX: 0, y: "0em", filter: "blur(0px)", transition: { type: "spring", duration: 0.5, bounce: 0.1 }, }, }; /** * A word inside a sentence that flips over to the next one on a timer: the * old word tips back on the X axis and fades, the new word's letters flip up * one after another, and the container's width springs between word lengths * so the surrounding text glides instead of jumping. * * It pauses on hover or focus, off-screen and in hidden tabs. Every word is * exposed once as visually hidden text for screen readers and search engines, * and under reduced motion the first word simply stays put. */ export function FlipWords({ words, interval = 3000, as = "span", letterStagger = 0.035, pauseOnHover = true, wordClassName, className, onPointerEnter, onPointerLeave, onFocus, onBlur, ...props }: FlipWordsProps) { const Comp = as as React.ElementType; const rootRef = React.useRef<HTMLElement>(null); const boxRef = React.useRef<HTMLSpanElement>(null); const measured = React.useRef(false); const reduceMotion = useReducedMotion(); const pageVisible = usePageInView(); const inView = useInView(rootRef, { amount: 0.5 }); const [hovered, setHovered] = React.useState(false); const [focused, setFocused] = React.useState(false); const [index, setIndex] = React.useState(0); const width = useMotionValue<number | "auto">("auto"); const count = words.length; const safeIndex = count ? index % count : 0; const paused = pauseOnHover && (hovered || focused); const running = count > 1 && !reduceMotion && inView && pageVisible && !paused; React.useEffect(() => { if (!running) return; const timer = setTimeout(() => setIndex((i) => (i + 1) % count), Math.max(1200, interval)); return () => clearTimeout(timer); }, [running, safeIndex, count, interval]); // Spring the box to the incoming word's width, and follow later size changes (fonts, breakpoints). React.useLayoutEffect(() => { const word = boxRef.current?.querySelector<HTMLElement>(`[data-flip-word="${safeIndex}"]`); if (!word) return; let controls: AnimationPlaybackControls | undefined; const target = word.offsetWidth; if (!measured.current || reduceMotion) { measured.current = true; width.jump(target); } else { controls = animate(width, target, { type: "spring", duration: 0.45, bounce: 0.1 }); } let first = true; const observer = new ResizeObserver(() => { if (first) { first = false; return; } controls?.stop(); width.jump(word.offsetWidth); }); observer.observe(word); return () => { controls?.stop(); observer.disconnect(); }; }, [safeIndex, reduceMotion, width]); const word = words[safeIndex] ?? ""; return ( <Comp ref={rootRef} data-slot="flip-words" className={cn(as === "span" || as === "strong" || as === "em" ? "inline-flex" : "flex", className)} onPointerEnter={(e: React.PointerEvent<HTMLElement>) => { setHovered(true); onPointerEnter?.(e); }} onPointerLeave={(e: React.PointerEvent<HTMLElement>) => { setHovered(false); onPointerLeave?.(e); }} onFocus={(e: React.FocusEvent<HTMLElement>) => { setFocused(true); onFocus?.(e); }} onBlur={(e: React.FocusEvent<HTMLElement>) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setFocused(false); onBlur?.(e); }} {...props} > <span className="sr-only">{words.join(", ")}</span> <motion.span ref={boxRef} aria-hidden style={{ width }} // Clip sideways only, so letters can tip above and below the line while flipping. className="relative inline-flex overflow-x-clip whitespace-nowrap" > <AnimatePresence mode="popLayout" initial={false}> <motion.span key={safeIndex} data-flip-word={safeIndex} className={cn("inline-block", wordClassName)} style={{ transformPerspective: PERSPECTIVE, transformOrigin: "50% 100%" }} initial="hidden" animate="visible" exit={{ opacity: 0, rotateX: 80, y: "-0.35em", filter: "blur(6px)", transition: { duration: 0.35, ease: [0.4, 0, 1, 1] }, }} variants={{ hidden: {}, visible: { transition: { staggerChildren: letterStagger } } }} > {graphemes(word).map((char, i) => ( <motion.span key={i} variants={letterVariants} className="inline-block whitespace-pre" style={{ transformPerspective: PERSPECTIVE, transformOrigin: "50% 100%" }} > {char} </motion.span> ))} </motion.span> </AnimatePresence> </motion.span> </Comp> ); }
Usage
import { FlipWords } from "@/components/dusk/flip-words/flip-words"
export function Tagline() {
return (
<h1 className="text-5xl font-bold">
Ship <FlipWords words={["faster", "calmer", "together"]} className="text-muted-foreground" />
</h1>
)
}Examples
Styles and timing
Style the word with className; the flip runs inside it. Set the pace with interval and the letter cascade with letterStagger.
Made for designers, builders, small teams
Deploy to edge, staging, production
import { FlipWords } from "@/components/dusk/flip-words/flip-words";
export default function FlipWordsStyles() {
return (
<div className="flex flex-col items-center gap-8 text-center">
<p className="text-3xl tracking-tight text-white/80">
Made for{" "}
<FlipWords
words={["designers", "builders", "small teams"]}
interval={2600}
className="font-serif text-white italic"
/>
</p>
<p className="text-2xl font-medium text-white/70">
Deploy to{" "}
<FlipWords
words={["edge", "staging", "production"]}
interval={2200}
letterStagger={0.05}
className="rounded-md border border-white/10 bg-white/5 px-2 text-white"
/>
</p>
</div>
);
}Inside a paragraph
Words of very different lengths are fine: the surrounding sentence glides as the width springs. Hover or focus pauses it (pauseOnHover).
The sentence around the word glides as the width springs from short, much, much longer, medium and back. Hover it to pause.
import { FlipWords } from "@/components/dusk/flip-words/flip-words";
export default function FlipWordsInline() {
return (
<p className="max-w-md text-center text-lg leading-relaxed text-white/65">
The sentence around the word glides as the width springs from{" "}
<FlipWords words={["short", "much, much longer", "medium"]} className="font-semibold text-white" /> and back.
Hover it to pause.
</p>
);
}API Reference
Also accepts any HTML attribute for the rendered element.
| Prop | Type | Default | Description |
|---|---|---|---|
| words | string[] | — | Words or short phrases to flip through. The first is server-rendered. |
| interval | number | 3000 | Milliseconds each word stays before flipping (minimum 1200). |
| as | "span" | "strong" | "em" | "p" | "div" | "h1" … "h6" | "span" | Element to render. span sits inline in a sentence. |
| letterStagger | number | 0.035 | Seconds between letters of the incoming word. |
| pauseOnHover | boolean | true | Pause while the pointer is over the word or focus is inside it. |
| wordClassName | string | — | Classes for each word. |
Accessibility
- Every word is exposed once as visually hidden text, so screen readers and crawlers get the full list instead of a word that keeps changing; the animated copy is aria-hidden.
- The first word is server-rendered with no entrance animation, so there's no flash or hydration mismatch.
- The rotation pauses on hover and focus, while off-screen and in hidden tabs.
- With prefers-reduced-motion it doesn't rotate at all: the first word stays put.