Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


`

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;

Edit eager-benji-rm14cb

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading