I am currently implementing the newest version 2.1.0 of react-id-swiper. I need to tell an external tool the current slide index every time the slides change. Therefore I am following the documentation to use the getSwiper prop to store the swiper instance in the component state using the useState hook and then send swiper.realIndex to the outside:
function MySwiper({ onSwipeChange }) {
const [swiper, updateSwiper] = useState(null);
const params = {
// ...
getSwiper: updateSwiper,
on: {
slideChange: () => {
onSwipeChange(swiper.realIndex);
}
}
// ...
};
return (
<Swiper {...params}>
// ...
</Swiper>
);
}
When I log out the swiper variable right before the return statement, it is null for the first render cycle and a proper Swiper instance for the second render cycle, when it has mounted. So the state seems to be correctly set.
Anyway, inside the slideChange callback the swiper state variable seems to be fixed to null. The callback never receives the instance.
Am I missing something or can I do it differently?
Hi @devbucket , there are 2 ways to add event listener to Swiper.
In your case, the first method won't work because swiper instance is always null initial render. We can achieve by the second one by using useEffect like below
const [currentIndex, updateCurrentIndex] = useState(0)
useEffect(
() => {
if (swiper !== null) {
swiper.on("slideChange", () => updateCurrentIndex(swiper.realIndex));
}
},
[swiper]
);
Here is the working demo
Great! That works! Thanks so much!
Most helpful comment
Hi @devbucket , there are 2 ways to add event listener to Swiper.
In your case, the first method won't work because
swiperinstance is alwaysnullinitial render. We can achieve by the second one by usinguseEffectlike belowHere is the working demo