reactjsreact-hooksresponsive-designswiper.jsreact-swiper

Is there a way to conditionally display the slidesPerView in React Swiper based on the Device screen resolution?


<Swiper
          slidesPerView={
            window.innerWidth <= 550
              ? 1
              : window.innerWidth <= 720
              ? 2
              : window.innerWidth > 720
              ? 3
              : 0
          }
          spaceBetween={30}
          pagination={{
            clickable: true,
          }}
          modules={[Pagination]}
          className="mySwiper"
        >
          {cardApi.map((card) => (
            <SwiperSlide>
              <div key={card.name} className="testimonial__card">
                <div className="testimonial__card-top">
                  <img src={card.profilePic} alt={card.name} />
                  <div>
                    <h4>{card.name}</h4>
                    <p>{card.position}</p>
                  </div>
                </div>
                <div className="testimonial__card-bottom">
                  <p>{card.comment}</p>
                </div>
              </div>
            </SwiperSlide>
          ))}
        </Swiper>

In the lines of code above, I'm trying to conditionally set the slides of a swiper based on the screen size (in order to make it responsive). The goal is to make 3 slides display on a (1280px) screen, 2 slides on a (720px) screen and lower, and a single slide on a (550px) screen and lower.

The code shared above does work eventually, but that is only after I refresh the page. I am hoping there'll be a better way to approach this issue where the slides will automatically adjust to the conditions immediately after resizing the screen without having to refresh the page again.


Solution

  • Based on what others have recommended, you need to setup an eventListener that listens for the resize event . This can be done inside a useEffect. On resize, it will then set the slides per view.

    The function that sets the slidesPerView:

    const setSlidesPerview = () => {
        setSlides(
          window.innerWidth <= 550
            ? 1
            : window.innerWidth <= 720
            ? 2
            : window.innerWidth > 720
            ? 3
            : 0
        );
      }
    

    The useEffect :

    React.useEffect(() => {
      // Initially set the amount of slides on page load
      setSlidesPerview();
      // Add the event listener on component mount
      window.addEventListener("resize", setSlidesPerview);
      // Remove the listener on unmount
      return () => {
        window.removeEventListener("resize", setSlidesPerview);
      };
    }, []);
    

    Here is an example on codesandbox : https://codesandbox.io/s/interesting-currying-uoxpw1?file=/src/App.js:538-772