'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
Solution 1:[1]
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>
)
}
Solution 2:[2]
just use this
const App = () => {
const [swiper, setSwiper] = useState(null);
const slideTo = (index) => {
if(swiper)
swiper.slideTo(index)};
return (
<Swiper onSwiper={setSwiper} >
{/* ... */}
</Swiper>
)
}
Solution 3:[3]
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>
)
}
Solution 4:[4]
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.
Solution 5:[5]
In typescript
I get the following error when trying to use onSwiper
:
Type 'Dispatch<SetStateAction<null>>' is not assignable to type '(swiper: Swiper) => void'
Am using the exact same code as in the demo.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kroleek |
Solution 2 | YoungHeart |
Solution 3 | |
Solution 4 | Marko Kova?evi? |
Solution 5 | Lee Probert |