Set react slick autoplayspeed dynamically without setState

1.3k Views Asked by At
    return {
      dots: false,
      arrows: true,
      infinite: true,
      speed: 300,
      slidesToShow: 1,
      centerMode: true,
      autoplay: true,
      cssEase: "linear",
      autoplaySpeed: 2000,
      centerPadding: '0px',
      prevArrow: <this.PrevArrow />,
      nextArrow: <this.NextArrow />,
    };
  } 
 PrevArrow(props: any) {
    const { onClick } = props;
    return (
      <div className={"left"} style={{ position: "absolute", right: "42px", bottom: "0", padding: "10px 15px", backgroundColor: "rgba(198, 198, 198)", zIndex: 999, height: "44px" }} onClick={onClick}><i className="fas fa-chevron-left"></i></div>
    );
  }

  NextArrow(props: any) {
    const { onClick } = props;
    return (
      <div className={"right"} style={{ position: "absolute", right: "0px", bottom: "0", padding: "10px 15px", backgroundColor: "rgba(198, 198, 198)", height: "44px" }} onClick={onClick} ><i className="fas fa-chevron-right"></i></div>
    );
  }

This is my settings for my slide

durationArray: any = [2000,2000,3000,5000,7000,10000]

This is my duration array for slides.

I want to slide first slide in 2000 miliseconds second slide 2000 miliseconds third slide 3000 miliseconds and so.

And I want to do it without setState cause when ever i do setState my react slick re-render and starts from beginning.

How can i do that?

1

There are 1 best solutions below

0
On

I prepared an example for you with my solution. I'm using setState (I afraid that you cannot do it without it) but Slider doesn't start from the beginning in my case. Follow the next link

https://codesandbox.io/s/react-slick-autospeed-7jlew?file=/src/App.js

const getSpeedForSlide = (slide) => {
  switch (slide) {
    case 1:
      return 1000;
    case 2:
      return 2000;
    case 3:
      return 3000;
    case 4:
      return 4000;
    default:
      return 1000;
  }
};

export default function App() {
  const [speed, setSpeed] = useState(1000);
  const handleAfterChange = useCallback((slide) => {
    setSpeed(getSpeedForSlide(slide));
  }, []);
  return (
    <div className="App">
      <Slider afterChange={handleAfterChange} autoplaySpeed={speed} autoplay>
        {[1, 2, 3, 4].map((item) => (
          <div key={item}>{item}</div>
        ))}
      </Slider>
    </div>
  );
}