Search code examples
svelteswiper.js

How to use Swiper JS method in Svelte


I want to use slideNext() method in Swiper JS. However, from the documentation of Swiper JS for Svelte, there is no example on showing how to access to method in Svelte. In React, there is a hook called useSwiper but no such thing in Svelte. Does anyone know how?


Solution

  • The API is a bit weird. It should be using a bindable prop but you need to handle the swiper event instead to get the API instance.

    <script>
      // ...
      let swiper;
    </script>
    
    <Swiper on:swiper={e => swiper = e.detail[0]}>
        <SwiperSlide>Slide 1</SwiperSlide>
        <SwiperSlide>Slide 2</SwiperSlide>
        <SwiperSlide>Slide 3</SwiperSlide>
    </Swiper>
    
    <button type=button on:click={() => swiper.slidePrev()}>Previous</button>
    <button type=button on:click={() => swiper.slideNext()}>Next</button>
    

    REPL example