How to display texts of an array one by one in React.js?

Advertisements

I’m working on a project which I need to display array of texts one by one.
each text should appear on screen after 5seconds, and last one should disappear.

I have tried map, forEach, setTimeOut and setInterval, but it seems like none of them is suitable.
map and forEach method only print out the array
setTimeOut runs one time,
and setInterval doesn’t print the last item.

here is my code, and I would really appreciate your help.


`

import { useState } from "react";

const Introduction = () => {

    const texts = [
        "text1",
        "text2",
        "text3",
    ];
    
    const [text, setText] = useState("text1");
    let index = 0;

    setInterval(() => {
        index++;
        if(index > texts.length) {
            index = 0;
        };
        setText(texts[index])
    }, 5000);

  return (
    <div>
        <div className='introduction-text'>
            <h1>{text}</h1>
        </div>
    </div>
  )
}

export default Introduction

`

>Solution :

Problem

  1. Every time the state changes index is set to 0
  2. Every time the state changes a new interval is created

Solution

  1. Use state to save the index between renders
  2. Move setInterval to useEffect to prevent adding new intervals
  3. You can get rid of text state now
import { useEffect, useState } from "react";

const texts = ["text1", "text2", "text3"];
const Introduction = () => {
  const [index, setIndex] = useState(0);

  useEffect(() => {
    const int = setInterval(() => {
      setIndex((index) => (index + 1) % texts.length);
    }, 5000);

    return () => clearInterval(int);
  }, [setIndex]);

  return (
    <div>
      <div className="introduction-text">
        <h1>{texts[index]}</h1>
      </div>
    </div>
  );
};

export default Introduction;

Leave a ReplyCancel reply