Search code examples
reactjsionic-frameworkionic5swiper.js

Ionic React Swiper not showing number of slides in slidesPerView property


enter image description here

I am using Ionic with React for the first time. While using the swiper, the number of slides per view property is not being respected and only 1 slide is being shown. What am I doing wrong?

I am using the following imports:

`import { Swiper, SwiperSlide } from 'swiper/react';

import 'swiper/swiper-bundle.css'`

<IonGrid>
    <IonRow>
       <IonCol size="3">
          <IonSelect
          onIonChange={((e) => {
            setForm({album: form.album, month: form.month, year: e.detail.value});
          })} 
          value={String(form.year)}>
            {[...Array(10)].map((num, i) =>
              <IonSelectOption 
                key={`year_${form.year - i}`}>
                  {form.year - i}
              </IonSelectOption>
            )}
          </IonSelect>
        </IonCol>
        <IonCol size="9">
          <Swiper 
          slidesPerView={6}
          onSwiper={(swiper) => console.log(swiper)} 
          onTap={(context) => onMonthTap(context)} 
          initialSlide={ form.month }>        
            {["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"].map((mon, idx) => {
              return (
                <>
                <SwiperSlide key={`month_${idx}`}>
                  <IonLabel>{form.month === idx ? <b>{mon}</b> : mon}</IonLabel>
                </SwiperSlide>
                </>
              )
            })}
          </Swiper>
        </IonCol>
      </IonRow>
  </IonGrid>

Solution

  • doing a swiper update helped but only after introducing some delay. I am not sure if this is the right answer or not but works for me for the time being.

    <Swiper 
      slidesPerView={6}
      spaceBetween={10}
      onSwiper={(swiper) => setSwiperInstance(swiper)}
      onTap={(context) => onMonthTap(context)} 
      initialSlide={ month }
    >    
    
    
    useEffect(() => {
      const timeout = setTimeout(() => {
        swiperInstance && swiperInstance.update();
      }, 50);
    }, [swiperInstance]);