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
- Every time the state changes
index
is set to 0 - Every time the state changes a new interval is created
Solution
- Use state to save the index between renders
- Move
setInterval
touseEffect
to prevent adding new intervals - 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;