Docs

Text Flip

Text with flipping effect

Installation

Update tailwind.config.js

Add the following to your tailwind.config.js file.

module.exports = {
  theme: {
    extend: {
      colors: {
        foreground: "hsl(var(--foreground))",
      },
      keyframes: {
        "flip-words": {
          "10%": { transform: "translateY(-112%)" },
          "25%": { transform: "translateY(-100%)" },
          "35%": { transform: "translateY(-212%)" },
          "50%": { transform: "translateY(-200%)" },
          "60%": { transform: "translateY(-312%)" },
          "75%": { transform: "translateY(-300%)" },
          "85%": { transform: "translateY(-412%)" },
          "100%": { transform: "translateY(-400%)" },
        },
      },
      animation: {
        "flip-words": "flip-words 8s infinite",
      },
    },
  },
};

Run the following command

It will create a new file called text-flip.tsx inside the components/animata/text directory.

mkdir -p components/animata/text && touch components/animata/text/text-flip.tsx

Paste the code

Open the newly created file and paste the following code:

"use client";
 
import { useEffect, useMemo, useRef } from "react";
 
export default function TextFlip() {
  const words = useMemo(() => ["fantastic", "love", "fire", "awesome", "fantastic"], []);
 
  const tallestRef = useRef<HTMLDivElement>(null);
 
  useEffect(() => {
    if (tallestRef.current) {
      let maxHeight = 0;
 
      words.forEach((word) => {
        const span = document.createElement("span");
        span.className = "absolute opacity-0";
        span.textContent = word;
        tallestRef.current?.appendChild(span);
        const height = span.offsetHeight;
        tallestRef.current?.removeChild(span);
 
        if (height > maxHeight) {
          maxHeight = height;
        }
      });
 
      tallestRef.current.style.height = `${maxHeight}px`;
    }
  }, [words]);
 
  return (
    <div className="box-content flex gap-4 text-3xl font-semibold">
      <p className="text-foreground">Coding is</p>
      <div ref={tallestRef} className="flex flex-col overflow-hidden text-blue-400">
        {words.map((word, index) => (
          <span key={index} className="animate-flip-words">
            {word}
          </span>
        ))}
      </div>
    </div>
  );
}

Credits

Built by Aashish Katila