magicuidesign / magicui

UI Library for Design Engineers. Animated components and effects you can copy and paste into your apps. Free. Open Source.
https://magicui.design
MIT License
8.62k stars 333 forks source link

How to provide `delay` for typing animation? #275

Open alamenai opened 3 weeks ago

alamenai commented 3 weeks ago

The component of Typing Animation has only three props:

image

However, I need to set a delay before the text even start typing.

alamenai commented 3 weeks ago

I tried this generated code from GPT but it did not work:

"use client"

import { useEffect, useState } from "react"
import { cn } from "@/lib/utils"

interface TypingAnimationProps {
  text: string
  duration?: number
  delay?: number // Add a delay prop
  className?: string
}

export default function TypingAnimation({
  text,
  duration = 200,
  delay = 0, // Default delay is 0
  className,
}: TypingAnimationProps) {
  const [displayedText, setDisplayedText] = useState<string>("")
  const [i, setI] = useState<number>(0)

  useEffect(() => {
    const startTyping = () => {
      const typingEffect = setInterval(() => {
        if (i < text.length) {
          setDisplayedText(text.substring(0, i + 1))
          setI(i + 1)
        } else {
          clearInterval(typingEffect)
        }
      }, duration)
    }

    const delayTimeout = setTimeout(() => {
      startTyping()
    }, delay)

    return () => {
      clearInterval(delayTimeout)
    }
  }, [duration, delay, 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>
  )
}
itsarghyadas commented 3 weeks ago

At what point do you want to introduce a 'delay'? If you can explain the animation scenario, I can help you.

alamenai commented 3 weeks ago

Yes, I have three cards that will be displayed one by one using framer motion.

If I display the CARD 01 and after 1 second, I'll display the CARD 02, then the typing should be start.

However, in the current state, when I display the CARD 02, the typing is already started typing for example 3 words.