Changing slides using buttons above swiper

Hi there, I’m new to Ionic React.

I’m trying to change slides using buttons that are placed above Swiper onClick:

const Tab: React.FC = () => {
  const swiper = useSwiper();

  return (
        <IonItem class="labels">
          <IonButton onClick={() => swiper.slideNext() }>
            <IonIcon  icon={chatbubbles} color="primary" />
            <IonLabel> Chat</IonLabel>
        <Swiper className="mySwiper"
          onSwiper={(swiper) => console.log(swiper)}
          onSlideChange={() => console.log('slide change')}

Since Swiper is not initialized before the button, how do I pass swiper to onClick? E.g.

Uncaught TypeError: Cannot read properties of null (reading 'slideNext')


See full source and video here.

Reference from answer on stackoverflow - reactjs - Ionic v5 React Ion-Slides: How to make a button to the next slide? - Stack Overflow

It’s easy
add this to your swiper navigation option
navigation={{ nextEl: "#swiper-forward", prevEl: "#swiper-back" }}
and then add the id to your buttons anywhere in the page

           <IonButton id="swiper-back" fill="clear">
              <IonIcon slot="icon-only" icon={chevronBackOutline}/>

Example of the structure

            modules={[Navigation, IonicSlides]}
            navigation={{ nextEl: "#swiper-forward", prevEl: "#swiper-back" }}
           <IonButton id="swiper-back" fill="clear">
              <IonIcon slot="icon-only" icon={chevronBackOutline}/>
            <IonButton id="swiper-forward" fill="clear">
              <IonIcon slot="icon-only" icon={chevronForwardOutline}/>

Thanks for the video. I’ve tried your solution before posting this. I got the same error as one of the comments in the video:

TypeScript error in /Users/macintosh/Desktop/theMagger/src/components/SlideContainer.tsx(19,26):
Object is possibly 'null'.  TS2531

    17 | 
    18 |   const handleSlideChange = async () => {
  > 19 |     const swiper = await mySlides.current.getSwiper();
       |                          ^
    20 |     // setDisablePrevBtn(swiper.isBeginning);
    21 |     // setDisableNextBtn(swiper.isEnd);
    22 |   };

Thanks for posing your solution. I’m thinking about navigating to any slide in the list of slides created. Your solution is designed to move back and forth between slides. Can it also be done using the navigation option for Slider?

1 Like

You need to just check for null and the error will go away.

You could use navigation but i dont mess up with that module a lot. There is a method in the swiper controller called “slideTo”, essentially takes the swiper view to the slide you pick. I am linking the doc for it Swiper API

Thanks! This is what I needed.

It seems to break on the current version. A workaround would be something like:

  const [swiperRef, setSwiperRef] = useState<any | null>(null);