Split Text

Reveals text character by character (or word by word) when it scrolls into view.

Install

$npx shadcn@latest add https://norvault.septiandwirestu.com/r/split-text.json

Or, with the @norvault namespace configured:

$npx shadcn@latest add @norvault/split-text

Source

"use client";

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

export type SplitTextProps = {
  text: string;
  as?: "h1" | "h2" | "h3" | "h4" | "p" | "span";
  splitBy?: "chars" | "words";
  /** Seconds before the first piece animates. */
  delay?: number;
  /** Seconds between pieces. */
  stagger?: number;
  /** Animate only the first time it enters the viewport. */
  once?: boolean;
  className?: string;
};

const piece: Variants = {
  hidden: { opacity: 0, y: "0.4em", filter: "blur(6px)" },
  visible: {
    opacity: 1,
    y: 0,
    filter: "blur(0px)",
    transition: { duration: 0.5, ease: [0.22, 1, 0.36, 1] },
  },
};

export function SplitText({
  text,
  as: Tag = "p",
  splitBy = "chars",
  delay = 0,
  stagger = 0.03,
  once = true,
  className,
}: SplitTextProps) {
  const reduceMotion = useReducedMotion();

  if (reduceMotion) return <Tag className={className}>{text}</Tag>;

  const words = text.split(" ");

  return (
    <Tag className={cn(className)} aria-label={text}>
      <motion.span
        aria-hidden
        initial="hidden"
        whileInView="visible"
        viewport={{ once, amount: 0.4 }}
        transition={{ staggerChildren: stagger, delayChildren: delay }}
      >
        {words.map((word, w) => (
          <span key={w} className="inline-block whitespace-nowrap">
            {splitBy === "words" ? (
              <motion.span className="inline-block" variants={piece}>
                {word}
              </motion.span>
            ) : (
              Array.from(word).map((char, c) => (
                <motion.span key={c} className="inline-block" variants={piece}>
                  {char}
                </motion.span>
              ))
            )}
            {w < words.length - 1 && " "}
          </span>
        ))}
      </motion.span>
    </Tag>
  );
}