Typing Animation

Characters appearing in typed animation

Typing Animation

Installation

Copy and paste the following code into your project.

"use client"
 
import { useEffect, useState } from "react"
 
import { cn } from "@/lib/utils"
 
interface TypingAnimationProps {
  text: string
  duration?: number
  className?: string
}
 
export function TypingAnimation({
  text,
  duration = 200,
  className,
}: TypingAnimationProps) {
  const [displayedText, setDisplayedText] = useState<string>("")
  const [i, setI] = useState<number>(0)
 
  useEffect(() => {
    const typingEffect = setInterval(() => {
      if (i < text.length) {
        setDisplayedText(text.substring(0, i + 1))
        setI(i + 1)
      } else {
        clearInterval(typingEffect)
      }
    }, duration)
 
    return () => {
      clearInterval(typingEffect)
    }
  }, [duration, i])
 
  return (
    <h1
      className={cn(
        "font-display text-center text-4xl font-bold leading-[5rem] tracking-[-0.02em] drop-shadow-sm",
        className
      )}
    >
      {displayedText ? displayedText : text}
    </h1>
  )
}

Update the import paths to match your project setup.

Props

PropTypeDescriptionDefault
classNamestringThe class name to be applied to the component
durationnumberDuration to wait in between each char type.200
textstringText to animate""