I have an array in React JS containing string data, I want to loop through that array and render each element of the array with some delay. I have tried setTimeout, setInterval but none of these work for me.
Instead, what I did I shifted that array into another array and put it in setTimeout so it might take some time but it didn't work for me
Here is the code
const [index, setIndex] = useState(0);
const [shiftArr, setShiftArr] = useState([]);
const fruitsArray = [
"Apple",
"Banana",
"Mango",
"Grapes",
"Peach",
"Avocado",
"watermelon",
"Pineapple",
"Orange",
"Strawbries",
];
useEffect(() => {
for (let i = 0; i < fruitsArray.length; i++) {
setTimeout(() => {
setShiftArr((shiftArr) => [...shiftArr, fruitsArray[i]]);
setIndex(i + 1);
}, 2000);
}
}, []);
Rendering shifted array
<div className="fruitList">
{shiftArr.map((fruit, ind) => (
<div style={{ marginLeft: "20px" }} key={ind}>
{fruit}
</div>
))}
</div>