Bill
Bill

Reputation: 5150

React TypeScript: Carousel: rotate an image every 3 seconds

I'm trying to rotate the image every 3 seconds but the images seem to load faster and faster the longer it runs for, it's like the set interval is being called many times not just once, do I need useEffect?

import React, { useState } from "react";
import image1 from "../images/carousel/screen-1.png";
import image2 from "../images/carousel/screen-2.png";
import image3 from "../images/carousel/screen-3.png";
import image4 from "../images/carousel/screen-4.png";
import image5 from "../images/carousel/screen-5.png";

const Carousel: React.FC = () => {

  interface StateInterface {
    showImage: string;
    startSlide: number;
  }

  const [state, setState] = useState<StateInterface>({
    showImage: image1,
    startSlide: 0
  });

  setInterval(() => {
   console.log('Im Starting'); // <== this prints many times, over and over
    const images = [image1, image2, image3, image4, image5]
    let currentIndex = state.startSlide;
    if (currentIndex < 5) currentIndex++;
    else currentIndex = 1;
    setState({ ...state, showImage: images[currentIndex], startSlide:currentIndex }); 
  }, 3000);

  return (
    <div className="carousel">
      <img src={state.showImage}></img>
    </div>
  );
};

export { Carousel };

Should showImage be type of string or HTMLObject?? or Similar??

Upvotes: 2

Views: 1005

Answers (1)

Naor Tedgi
Naor Tedgi

Reputation: 5707

you are trying to assign a variable from a string. it's like trying to do this

const x ="Carousel" 
x()

just add all the images to an array and instead of itrate their names return the there index inside the array

and add startSlide to the state

 interface StateInterface {
    showImage: string;
    startSlide:int
  }


  setInterval(() => {
    const images = [image1, image2, image3, image4, image5]
    let currentIndex = this.state.startSlide
    if (startSlide < 5) currentIndex++;
    else currentIndex = 1;
    setState({ ...state, showImage: images[currentIndex], startSlide:currentIndex }); 
  }, 3000);

Upvotes: 1

Related Questions