kidjp85 / react-id-swiper

A library to use idangerous Swiper as a ReactJs component which allows Swiper's modules custom build
https://react-id-swiper.ashernguyen.site/
MIT License
1.49k stars 154 forks source link

Question: Controlled swiper #489

Closed MildTomato closed 3 years ago

MildTomato commented 3 years ago

Controlling the index of Swiper component

Can the Swiper component be controlled externally, so that an 'active id' could be set?

This is so an external navigation could be used, that could allow the swiper to 'jump' to a specific index.

I would of expected something like this maybe...


const [activeId, setActiveId] = useState(0) 

<Swiper
  activeId={activeId}
  onActiveIndexChange={(slider) => setActiveId(slider.activeIndex)}
...
>
MildTomato commented 3 years ago

Nevermind, answered my own question.

For anyone else interested, here's how to do it.

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

  return (
    <>
      {/* Controls outside of Swiper that use swiper instance */}
      <button onClick={() => swiper.slideTo(0)}>Go to 1st slide</button>
      <button onClick={() => swiper.slideTo(1)}>Go to 2nd slide</button>
      {/* Swiper component */}
      <Swiper onSwiper={setSwiper} slidesPerView={1}>
        <SwiperSlide>first slide</SwiperSlide>
        <SwiperSlide>2nd slide</SwiperSlide>
      </Swiper>
    </>
  );
}
carlosqdev commented 2 years ago

Excellent thanks

ogheneovo12 commented 2 years ago

this

Nevermind, answered my own question.

For anyone else interested, here's how to do it.

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

  return (
    <>
      {/* Controls outside of Swiper that use swiper instance */}
      <button onClick={() => swiper.slideTo(0)}>Go to 1st slide</button>
      <button onClick={() => swiper.slideTo(1)}>Go to 2nd slide</button>
      {/* Swiper component */}
      <Swiper onSwiper={setSwiper} slidesPerView={1}>
        <SwiperSlide>first slide</SwiperSlide>
        <SwiperSlide>2nd slide</SwiperSlide>
      </Swiper>
    </>
  );
}

how do i get the most recent active/real index