Home > Enterprise >  Can autoPlay SwipperJS disabled and enabled programmatically?
Can autoPlay SwipperJS disabled and enabled programmatically?

Time:11-18

So I have multiple arrays with different lengths. I want to show it in swiper. is it possible to enable the autoplay in Swipper if the number of items in the array is more than 5 and disable it if it is less than that?

CodePudding user response:

Yes it's possible. You have 2 options.

First option is to render the Swipper component conditionally like this:

if(myArray.length > 5) {
  return (
   <Swiper
      spaceBetween={50}
      slidesPerView={3}
      autoplay={{
        delay: 2500,
        disableOnInteraction: false,
      }}
   >
      <SwiperSlide>Slide 1</SwiperSlide>
      <SwiperSlide>Slide 2</SwiperSlide>
      <SwiperSlide>Slide 3</SwiperSlide>
      <SwiperSlide>Slide 4</SwiperSlide>
      ...
   </Swiper>
  );
} else {
  return (
   <Swiper
      spaceBetween={50}
      slidesPerView={3}
   >
      <SwiperSlide>Slide 1</SwiperSlide>
      <SwiperSlide>Slide 2</SwiperSlide>
      <SwiperSlide>Slide 3</SwiperSlide>
      <SwiperSlide>Slide 4</SwiperSlide>
      ...
   </Swiper>
  );
}

And the second way you can do this is to enable it by default and then use the stop method to stop it like this (You can see the examples here):

useEffect(() => {
  if(myArray.length < 5) {
    swiper.autoplay.stop()
  }
}, [myArray]);

return (
 <Swiper
    spaceBetween={50}
    slidesPerView={3}
    autoplay={{
      delay: 2500,
      disableOnInteraction: false,
    }}
 >
    <SwiperSlide>Slide 1</SwiperSlide>
    <SwiperSlide>Slide 2</SwiperSlide>
    <SwiperSlide>Slide 3</SwiperSlide>
    <SwiperSlide>Slide 4</SwiperSlide>
    ...
 </Swiper>
);
  • Related