Carlo Carpio
Carlo Carpio

Reputation: 141

Setting the active slide in swiper/react with react state

I would like to ask if there is a way to control/set the active slide with swiper/react?

I have tried to handle the onSwiper function with props but still cant update the slide index.

Thank you

Upvotes: 14

Views: 51883

Answers (5)

MarcosCunhaLima
MarcosCunhaLima

Reputation: 301

You can setup a component to do just that (change slide) and stuff it inside (this is important) component.

   const ChangeSlide = ({ position }) => {
      const swiper = useSwiper()

      useEffect(() => {
         if (swiper) {
            swiper.slideTo(position)
         }
      }, [swiper, position])
      return null
   }

then stuff it inside <Swipe> component:

<Swiper ...>
   <ChangeSlide position={2} />
   <Swiperlide> ... </SwiperSlide>
   <Swiperlide> ... </SwiperSlide>
   <Swiperlide> ... </SwiperSlide>
</Swiper>

Upvotes: 0

Marko Kovačević
Marko Kovačević

Reputation: 54

The newer option is to set initialSlide={specificIndex} on <Swiper> instance. If you know which index you want to slide to, just set "initialSlide" prop for Swiper.

Like here:

<Swiper initialSlide={clickedIndex}>

    <SwiperSlide>
        Slide content 1
    </SwiperSlide>
    <SwiperSlide>
        Slide content 2
    </SwiperSlide>
    <SwiperSlide>
        Slide content 3
    </SwiperSlide>

</Swiper>

I test this only in React 17.

Upvotes: 1

Wei Hung
Wei Hung

Reputation: 71

You can use useSwiper to get the swiper instance inside Swiper on React, and then freely control behaviors of the Swiper including using slideTo method.

Like:

import { Swiper, useSwiper } from 'swiper/react'

const SomethingInsideSwiper = () => {
  const swiper = useSwiper()

  // on click
  const handleOnSetSwiper = () => {
    swiper.slideTo(/* index */)
  }

  // or use side effect
  useEffect(() => {
    swiper.slideTo(/* index */)
  }, /* [state] if you need controlled by a state */)

  return (<>{/* ...... /*}</>)
}

const App = () => {
  return (
    <Swiper {/* SwiperProps */} >
      <SomethingInsideSwiper />
    </Swiper>
  )
}

Upvotes: 1

YoungHeart
YoungHeart

Reputation: 31

just use this

const App = () => {
 
  const [swiper, setSwiper] = useState(null);

  const slideTo = (index) => {
if(swiper) 
swiper.slideTo(index)};

  return (
      <Swiper onSwiper={setSwiper} >
        {/* ... */}
      </Swiper>
  )
}

Upvotes: 3

Kroleek
Kroleek

Reputation: 251

You can use swiper instance to access swiper API (https://swiperjs.com/api/) and there is method slideTo.

So in code example it can looks like this

const App = () => {
  // store swiper instance
  const [swiper, setSwiper] = useState(null);

  const slideTo = (index) => swiper.slideTo(index);

  return (
      <Swiper onSwiper={setSwiper} >
        {/* ... */}
      </Swiper>
  )
}

Upvotes: 25

Related Questions