swiper: Swiper incorrectly warns about a wrong number of slides for loop mode

Check that this is really a bug

  • I confirm

Reproduction link

https://codesandbox.io/p/devbox/swiper-react-infinite-loop-vfz433?file=%2Fsrc%2FApp.jsx

Bug description

If you attempt to render a basic loop swiper with any number of slides within jest tests the swiper warns about the incorrect number of slides when it shouldn’t

The Swiper

import { Autoplay, Navigation, Pagination } from 'swiper/modules';
import { Swiper, SwiperSlide } from 'swiper/react';

const modules = [Navigation, Pagination, Autoplay];

export const App = () => {
  return (
    <Swiper
      loop
      slidesPerView={1}
      slidesPerGroup={1}
      loopAddBlankSlides
      modules={modules}
    >
      <SwiperSlide>test</SwiperSlide>
      <SwiperSlide>test</SwiperSlide>
      <SwiperSlide>test</SwiperSlide>
      <SwiperSlide>test</SwiperSlide>
      <SwiperSlide>test</SwiperSlide>
      <SwiperSlide>test</SwiperSlide>
    </Swiper>
  );
};

the test

import { render } from '@testing-library/react';

import { App } from './abc';

describe('App', () => {
  it('App', () => {
    render(<App />);
  });
});

[!CAUTION] Swiper Loop Warning: The number of slides is not enough for loop mode, it will be disabled and not function properly. You need to add more slides (or make duplicates) or lower the values of slidesPerView and slidesPerGroup parameters

Expected Behavior

No warning

Actual Behavior

Warning

Swiper version

11.1.4

Platform/Target and Browser Versions

macOS 14.5

Validations

  • Follow our Code of Conduct
  • Read the docs.
  • Check that there isn’t already an issue that request the same feature to avoid creating a duplicate.
  • Make sure this is a Swiper issue and not a framework-specific issue

Would you like to open a PR for this bug?

  • I’m willing to open a PR

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 22
  • Comments: 29

Most upvoted comments

<section className={"w-full"}>
     <Swiper
       autoplay={{
         delay: 2500,
         disableOnInteraction: false,
         pauseOnMouseEnter: true
       }}
       breakpoints={
         {
           768: {
             slidesPerView: 3,
           }
         }
       }
       centeredSlides={true}
       className={``}
       coverflowEffect={{
         rotate: 0,
         slideShadows: false
       }}
       effect={"fade"}
       grabCursor={true}
       loop={products.length >= 4}
       slidesPerView={1}
       spaceBetween={0}
     >
       {products.map((item, index) => {
         return (
           <SwiperSlide
             key={index}
             className={``}
           >
             <ProductItem product={item} />
           </SwiperSlide>
         );
       })}
     </Swiper>
   </section>
   
my code, this ok

loop={products.length >= 4}

Had the same issue - now using swiper element in Vue 3 as swiper/vue is outdated/i just couldn’t get it to work correctly.

IT DID NOT WORK IN 11.x. for me without doing it this way.

The key is to use init=“false” attribute and then pass the params, loop especially, as html element properties.

<template>
  <swiper-container
    ref="swiperEl"
    v-if="items && items.length > 0"
    :init="false"
  >
    <swiper-slide v-for="(item, idx) in items" :key="idx">
      {{ item.Title }}
    </swiper-slide>
  </swiper-container>
</template>

<script setup>
import { register } from 'swiper/element/bundle';
import { ref, onMounted } from 'vue';

const items = [
  {
    ID: "ID1",
    Title: "Event1",
    BannerImg: "madison.jpg",
  },
  {
    ID: "ID2",
    Title: "Event2",
    BannerImg: "quiz.png",
  },
  {
    ID: "ID3",
    Title: "Event3",
    BannerImg: "madison.jpg",
  },
  {
    ID: "ID4",
    Title: "Event4",
    BannerImg: "quiz.png",
  },
];

// Ref attached to swiper
const swiperEl = ref('swiperEl');

const mods = [EffectFade];
const spaceBetween = 16;

const swiperParams = {
  modules: mods,
  slidesPerView: 1,
  spaceBetween: spaceBetween,
  breakpoints: {
    640: {
      slidesPerView: 2,
    },
    1024: {
      slidesPerView: 3,
    },
  },
  on: {
    init() {
      console.log('Swiper initialized!');
      this.params.loop = true;
    },
  },
};

onMounted(() => {

  // Swiper initialization
  register();

  // Ensure it's ready
  if (!swiperEl.value) {
    return;
  }

  // Assign parameters to swiper element and then init
  Object.assign(swiperEl.value, swiperParams);

  swiperEl.value.initialize();
});
</script>

Warning is now gone, swiper loops and can be swiped correctly.

DOCS HERE

I made the cyclic slide show work. Swiper version 11.1.14. I used swiper/vue, not swiper/react. But I think you can solve the same thing in React. Two things prevented the work. The first is if the slides are not statically defined, but are added dynamically. The second is that the number of slides must be greater than the slides per view.

In order for Swiper to detect slides, you need to call the update method for the swiper instance after constructing the DOM. I call update for swiper after a second to make sure DOM is built (onMounted). Getting an instance of swiper is also quite a quest. The documentation has a way via useSwiper, but it doesn’t work and displays an error. I found a way to get an instance of swiper in the script to call its methods via @swiper. Code example for swiper/vue:

<template>
  <ion-page>
    <ion-content :fullscreen="true">
      <ion-title class="ion-text-center ion-padding-vertical">Популярные события</ion-title>
      <swiper :modules="modules" :slides-per-view="2" :space-between="10" :autoplay="true" navigation
        @swiper="onSwiper" :pagination="{clickable: true}" :loop="true"
      >
        <template v-for="slide in slides" :key="slide.ID">
          <swiper-slide>
            <ion-img :src="'/src/assets/slides/'+slide.BannerImg"></ion-img>
          </swiper-slide>
        </template>
      </swiper>

      <Categories />
    </ion-content>
  </ion-page>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref } from 'vue';
  import { Pagination, Navigation, Autoplay } from 'swiper/modules';
  import { Swiper, SwiperSlide } from 'swiper/vue';
  import { IonPage, IonTitle, IonContent, IonImg } from '@ionic/vue';

  import 'swiper/css';
  import 'swiper/css/autoplay';
  import 'swiper/css/pagination';
  import '@ionic/vue/css/ionic-swiper.css';

  export default defineComponent({
    components: { IonPage, IonContent, IonTitle, IonImg, Swiper, SwiperSlide },
    setup() {
      const slides = [
        {
            ID: "ID1",
            Title: "Event1",
            BannerImg: "madison.jpg",
        },
        {
            ID: "ID2",
            Title: "Event2",
            BannerImg: "quiz.png",
        },
        {
            ID: "ID3",
            Title: "Event3",
            BannerImg: "madison.jpg",
        },
        {
            ID: "ID4",
            Title: "Event4",
            BannerImg: "quiz.png",
        }];
      const swiper = ref<any>(null);
      const onSwiper = (instance: any) => {
        swiper.value = instance;
      }
      onMounted(() => {
        setTimeout(() => {
          swiper.value.update();
        }, 1);
      });

      return {
        slides, onSwiper,
        modules: [Autoplay, Navigation, Pagination],
      };
    },
  });
</script>

In my experience this warning is triggered when the check for this warning takes place before the hosting app has rendered the slide elements in the DOM, resulting in functional behaviour, but a false positive on the warning.

Didn’t find a clean solution yet, but was able to avoid the warning by using a mutation observer in my UI component and only construct the Swiper instance after all slides were made available in the DOM.

I assume the check for this warning should take place somewhere else during Swiper construction.