Reputation: 389
Is there a way to attached an event with the instance of swiperjs in react? I tried using the method below but it won't recognize the on event of slideChange.
import React, { useEffect, useRef } from 'react';
import Swiper from 'swiper';
const Slider = () => {
const swiperReference = useRef(null);
const params = {
on: {
slideChange: () => {
console.log('swiper change');
},
},
};
useEffect(() => {
swiperReference.current = new Swiper('.swiper-container', params);
}, []);
return (
<div class="swiper-container">
<div class="swiper-wrapper">
<!-- Slides -->
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
</div>
<div class="swiper-pagination"></div>
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
</div>
);
};
export default Slider;
Upvotes: 6
Views: 8716
Reputation: 636
You can get the Swiper onSlideChange event the React way using the onSlideChange prop, like this:
There's no need to instantiate Swiper in your useEffect hook. You only have to call the Swiper component in your JSX template like so:
<Swiper
className={"my-slider"}
loop={true}
onSlideChange={(swiperCore) => {
const {
activeIndex,
snapIndex,
previousIndex,
realIndex,
} = swiperCore;
console.log({ activeIndex, snapIndex, previousIndex, realIndex });
}}
Upvotes: 9