SwiperSlide onTouchStart/onClick => trigger slideNext()

Viewed 7153

I want to include this slideshow: https://swiperjs.com/react/

As I find it not very comfortable to drag for the next slide, I want to add an onClick event to the full Slider so the next slide comes.

How can I trigger a slideNext() in React? I have problems reading the documentation / I do not understand it - and it seems the documentation does not tell how to do this in react.

In jquery it would be something like this :

$('section.slideshow').on( 'click', function() {
    swiper.slideNext();
});

Here is my react code :

import React from 'react'
import SwiperCore, { Navigation, Pagination, A11y } from 'swiper'
import { Swiper, SwiperSlide } from 'swiper/react'

import 'swiper/swiper.scss'
import 'swiper/components/navigation/navigation.scss'
import 'swiper/components/pagination/pagination.scss'

SwiperCore.use([Navigation, Pagination, A11y])


function Page(){
  return (
    <div>

<Swiper 
  onClick={() => console.log('click')}
  onTouchStart={() => slideNext()     }
>

  <SwiperSlide>slide 1</SwiperSlide>
  <SwiperSlide>slide 2</SwiperSlide>

</Swiper>

</div>

  );
}

export default Page;
3 Answers

For React Hooks

Define a useState like this:

const [my_swiper, set_my_swiper] = useState({});

Then in your swiper define it like this:

<Swiper 
    slidesPerView={1}
    onInit={(ev) => {
        set_my_swiper(ev)
    }}>
        <SwiperSlide>
            <div>
                Slide 1
            </div>
        </SwiperSlide>
        <SwiperSlide>
            <div>
                Slide 2
            </div>
        </SwiperSlide>
</Swiper>

Notice the onInit method to bind to your variable.

Then you can use my_swiper hook to call next/previous functions like this.

my_swiper.slideNext();
my_swiper.slidePrev();

You can call these anywhere to dynamically control your swiper.

Also you can navigate to any slide

my_swiper.slideTo(number);

I used it as below:

<Swiper
                        getSwiper={this.updateSwiper}
                        {...params}
                        
                    >{/*modules={[Navigation]}*/}
                        {items}
                    </Swiper>

by these functions:

updateSwiper(value:any) {
    this.setState({
        swiper: value
    });
}

goNext = () => {
    if (this.state.swiper !== null) {
        this.state.swiper.slideNext();
    }
};
Related