Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swiper - how to hide and show navigation at breakpoints? (React)

I got React Typescript swiper slider styled with tailwind. Everything works correctly, as long as I hide the navigation when I resize it. To hide the navigation I use the tailwind style 'hidden', but when I show the navigation again it stops working. How to correctly hide/show navigation in react on different brackpoints?

import { Navigation, Pagination } from 'swiper';
import { Swiper, SwiperSlide } from "swiper/react";
import 'swiper/css';
import 'swiper/css/navigation';

const Slider = ({slides}) => {
  const prevRef = useRef<HTMLButtonElement>(null);
  const nextRef = useRef<HTMLButtonElement>(null);

  return (
    <div>
      <Swiper
        slidesPerView={'auto'}
        spaceBetween={16}
        className='custom-swiper-slide'
        navigation={{
          enabled: true,
          nextEl: nextRef.current,
          prevEl: prevRef.current,
          disabledClass: 'opacity-40',
        }}
        breakpoints={{
          320: {
            slidesPerView: 'auto',
            spaceBetween: 8,
            //navigation: {enabled: false} - not working!
            //navigation: {hidden: true} - not working!
          },
          640: {
            slidesPerView: 1,
            spaceBetween: 16,
          }
        }}
        onBeforeInit={(swiper) => {
          if (swiper.params.navigation && typeof swiper.params.navigation !== 'boolean') {
            swiper.params.navigation.prevEl = prevRef.current;
            swiper.params.navigation.nextEl = nextRef.current;
          }
        }}
        modules={[Navigation]}
      >
        {slides.map((slide) => {
          return (
            <SwiperSlide>
             ...slide...
            </SwiperSlide>
          )})
        }
      </Swiper>
      <div className='hidden md:block'> // show/hide nav buttons
      // After the buttons have been hidden once, they stop working, they appear but don't work
        <button ref={prevRef}>prev</button>
        <button ref={nextRef}>next</button>
      </div>
    </div>
  );
}
like image 448
Lex2000 Avatar asked Dec 17 '25 12:12

Lex2000


1 Answers

Try to move the navigation to breakpoints:

breakpoints={{
          320: {
            navigation: {
              enabled: true,
              nextEl: nextRef.current,
              prevEl: prevRef.current,
            },
          },
          640: {
            navigation: {
              enabled: true,
              nextEl: nextRef.current,
              prevEl: prevRef.current,
              disabledClass: 'opacity-40',
            },
          }
like image 69
Will Black Avatar answered Dec 19 '25 02:12

Will Black



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!