itsmarcotime
itsmarcotime

Reputation: 15

React JS - How to add a delay to text inside a component

I have a React component with some text inside, but I want each line of text to render with a 2 second delay. However, I am having some trouble wrapping my head around the execution of the code. I am using React and JavaScript. I was thinking of using some kind of hook here but not sure if I have the right idea.. Any help would be appreciated.

import React from "react";

function Home() {
    return (
        <div>
           <p>Render after 2 seconds</p><br />
           <p>Render after 4 seconds</p><br />
           <p>Render after 6 seconds</p><br />
           <p>Render after 8 seconds</p>
        </div>
    );
};

export default Home;

Upvotes: 1

Views: 1281

Answers (1)

Arkellys
Arkellys

Reputation: 7790

You can use setTimeout and useEffect to do that. Here is an example:

function Home() {
  const [texts, setTexts] = useState([]);

  useEffect(() => {
    const timeoutIds = [];

    ["Text 1", "Text 2", "Text 3", "Text 4"].forEach((text, i) => {
      const timeoutId = setTimeout(() => {
        setTexts((prev) => [...prev, text]);
      }, 2000 * i);

      timeoutIds.push(timeoutId);
    });

    return () => {
      timeoutIds.forEach((id) => clearTimeout(id));
    };
  }, []);

  return (
    <div>
      {texts.map((text) => (
        <p key={text}>{text}</p>
      ))}
    </div>
  );
}

CodeSandbox demo

Upvotes: 3

Related Questions