Huzaifa Zahid
Huzaifa Zahid

Reputation: 37

Issue with Swiper.jsBreakpoints in React for Different Screen Sizes

I'm using Swiper.jsin a React project and having trouble with setting up breakpoints to display a different number of slides per view based on screen size. My goal is to show 2 slides on small screens (786px and above), 3 slides on medium screens (1080px and above), and 4 slides on large screens (1200px and above). However, the breakpoints don't seem to be working correctly. Here's my current code:


    <Swiper
           breakpoints={{
            0: { slidesPerView: 1 },
            786: { slidesPerView: 2 },
            1080: { slidesPerView: 3 },
          }}
            slidesPerView={4}
            spaceBetween={30}
            pagination={{
              clickable: true,
            }}
            modules={[Pagination]}
            className="mySwiper"
           
          >
            <SwiperSlide>Slide 1</SwiperSlide>
        <SwiperSlide>Slide 2</SwiperSlide>
        <SwiperSlide>Slide 3</SwiperSlide>
        <SwiperSlide>Slide 4</SwiperSlide>
        <SwiperSlide>Slide 5</SwiperSlide>
        <SwiperSlide>Slide 6</SwiperSlide>
        <SwiperSlide>Slide 7</SwiperSlide>
        <SwiperSlide>Slide 8</SwiperSlide>
        <SwiperSlide>Slide 9</SwiperSlide>
          </Swiper>


Upvotes: 0

Views: 49

Answers (1)

Build Though
Build Though

Reputation: 442

Try once after changing slidesPerView={1} or removing this prop also check swipper css too like is it working properly or not. This was my implementation

import React, { useState } from 'react';
import { Swiper, SwiperSlide } from 'swiper/react';
import SwiperCore, { Navigation } from 'swiper';
import './styles.css';
import 'swiper/swiper-bundle.css';

SwiperCore.use([Navigation]);

export default () => {
  const slides = [];
  for (let i = 0; i < 5; i += 1) {
    slides.push(
      <SwiperSlide key={`slide-${i}`} tag="li" style={{ listStyle: 'none' }}>
        <img
          style={{ width: '100%' }}
          src={`https://picsum.photos/id/${i + 1}/500/300`}
          alt={`Slide ${i}`}
        />
      </SwiperSlide>
    );
  }

  return (
    <React.Fragment>
      <div id="title">Resize window to see responsiveness</div>
      <Swiper
        breakpoints={{
          // when window width is >= 640px
          640: {
            width: 640,
            slidesPerView: 1,
          },
          // when window width is >= 768px
          768: {
            width: 768,
            slidesPerView: 2,
          },
        }}
        id="main"
        width="480"
        navigation
        spaceBetween={5}
        slidesPerView={1}
      >
        {slides}
      </Swiper>
      <div id="bp-wrapper">
        <span id="bp-480">480p breakpoint</span>
        <span id="bp-640">640p breakpoint</span>
        <span id="bp-768">768p breakpoint</span>
      </div>
    </React.Fragment>
  );
};

Upvotes: 0

Related Questions