Sign up and get 15% off the four courses and Lifetime.

Cut reveal

Each letter or word slides up from behind an invisible line, one after another. Made for your name, a page title or a big statement, and it can wait until it scrolls into view.

Free·React and Tailwind

Try it

How to use this

  1. 01

    Make a file called cut-reveal.tsx in your project's components folder.

  2. 02

    Install what it needs: npm install framer-motion

  3. 03

    Paste the code in, keeping the licence note at the top.

  4. 04

    Import it where you want it and change the words, colours and sizes to yours.

The code

cut-reveal.tsx
/**
 * MIT License
 *
 * Copyright (c) 2024 Daniel Petho
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
"use client";

import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import { motion, type Transition, useInView, useReducedMotion } from "framer-motion";

const cn = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");

const splitIntoCharacters = (text: string): string[] => {
  if (typeof Intl !== "undefined" && "Segmenter" in Intl) {
    const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
    return Array.from(segmenter.segment(text), ({ segment }) => segment);
  }
  return Array.from(text);
};

export interface CutRevealProps {
  children: React.ReactNode;
  /** Pieces drop in from above instead of rising from below. */
  reverse?: boolean;
  transition?: Transition;
  /** Animate by "characters", "words", "lines" or any separator string. */
  splitBy?: "words" | "characters" | "lines" | string;
  /** Seconds between each piece starting. */
  staggerDuration?: number;
  staggerFrom?: "first" | "last" | "center" | "random" | number;
  containerClassName?: string;
  wordLevelClassName?: string;
  elementLevelClassName?: string;
  onClick?: () => void;
  onStart?: () => void;
  onComplete?: () => void;
  /** Start on mount. */
  autoStart?: boolean;
  /** Wait until the text scrolls into view, then start once. Overrides autoStart. */
  startInView?: boolean;
}

export interface CutRevealRef {
  startAnimation: () => void;
  reset: () => void;
}

interface WordObject {
  characters: string[];
  needsSpace: boolean;
}

export const CutReveal = forwardRef<CutRevealRef, CutRevealProps>(
  (
    {
      children,
      reverse = false,
      transition = { type: "spring", stiffness: 190, damping: 22 },
      splitBy = "words",
      staggerDuration = 0.2,
      staggerFrom = "first",
      containerClassName,
      wordLevelClassName,
      elementLevelClassName,
      onClick,
      onStart,
      onComplete,
      autoStart = true,
      startInView = false,
    },
    ref,
  ) => {
    const containerRef = useRef<HTMLSpanElement>(null);
    const inView = useInView(containerRef, { once: true, amount: 0.4 });
    const reduceMotion = useReducedMotion();
    const text = typeof children === "string" ? children : children?.toString() || "";
    const [isAnimating, setIsAnimating] = useState(false);

    const elements = useMemo(() => {
      const words = text.split(" ");
      if (splitBy === "characters") {
        return words.map((word, i) => ({ characters: splitIntoCharacters(word), needsSpace: i !== words.length - 1 }));
      }
      return splitBy === "words" ? text.split(" ") : splitBy === "lines" ? text.split("\n") : text.split(splitBy);
    }, [text, splitBy]);

    const getStaggerDelay = useCallback(
      (index: number) => {
        const total =
          splitBy === "characters"
            ? (elements as WordObject[]).reduce((acc, word) => acc + word.characters.length + (word.needsSpace ? 1 : 0), 0)
            : elements.length;
        if (staggerFrom === "first") return index * staggerDuration;
        if (staggerFrom === "last") return (total - 1 - index) * staggerDuration;
        if (staggerFrom === "center") return Math.abs(Math.floor(total / 2) - index) * staggerDuration;
        if (staggerFrom === "random") return Math.abs(Math.floor(Math.random() * total) - index) * staggerDuration;
        return Math.abs(staggerFrom - index) * staggerDuration;
      },
      [elements, splitBy, staggerFrom, staggerDuration],
    );

    const startAnimation = useCallback(() => {
      setIsAnimating(true);
      onStart?.();
    }, [onStart]);

    useImperativeHandle(ref, () => ({ startAnimation, reset: () => setIsAnimating(false) }));

    useEffect(() => {
      if (startInView ? inView : autoStart) startAnimation();
      // Starts once, when it mounts or first comes into view.
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [autoStart, startInView, inView]);

    const baseDelay = typeof transition?.delay === "number" ? transition.delay : 0;
    const variants = {
      hidden: { y: reverse ? "-100%" : "100%" },
      visible: (i: number) => ({
        y: 0,
        transition: reduceMotion ? { duration: 0 } : { ...transition, delay: baseDelay + getStaggerDelay(i) },
      }),
    };

    const words: WordObject[] =
      splitBy === "characters"
        ? (elements as WordObject[])
        : (elements as string[]).map((el, i) => ({ characters: [el], needsSpace: i !== elements.length - 1 }));

    return (
      <span
        className={cn(containerClassName, "flex flex-wrap whitespace-pre-wrap", splitBy === "lines" && "flex-col")}
        onClick={onClick}
        ref={containerRef}
      >
        <span className="sr-only">{text}</span>
        {words.map((wordObj, wordIndex, array) => {
          const previousCharsCount = array.slice(0, wordIndex).reduce((sum, word) => sum + word.characters.length, 0);
          return (
            <span key={wordIndex} aria-hidden="true" className={cn("inline-flex overflow-hidden", wordLevelClassName)}>
              {wordObj.characters.map((char, charIndex) => (
                <span className={cn(elementLevelClassName, "relative whitespace-pre-wrap")} key={charIndex}>
                  <motion.span
                    custom={previousCharsCount + charIndex}
                    initial="hidden"
                    animate={isAnimating ? "visible" : "hidden"}
                    variants={variants}
                    onAnimationComplete={
                      wordIndex === array.length - 1 && charIndex === wordObj.characters.length - 1 ? onComplete : undefined
                    }
                    className="inline-block"
                  >
                    {char}
                  </motion.span>
                </span>
              ))}
              {wordObj.needsSpace && <span> </span>}
            </span>
          );
        })}
      </span>
    );
  },
);

CutReveal.displayName = "CutReveal";
NextLine shadow text