react-id-swiper
react-id-swiper copied to clipboard
"reachEnd" bahavior weird with "loop" mode
Problem
I have 3 slides with loop && use the instance to register the reachEnd
[ 1 2 3 ]
- I swipe to "3"
[ 1 2 "3" ]
The "reachEnd" does not call
- From slide "3", I swipe
forwardto go back to the first slide "1"
[ "1" 2 3 ]
The "reachEnd" now calls
But it is the first slide not the final slide.
Question
Is it the expectation behavior?
Code
To re-produce
import React from 'react';
import './App.css';
import 'swiper/css/swiper.css';
import { Swiper, Navigation, Pagination } from 'swiper/js/swiper.esm';
import ReactIdSwiperCustom from 'react-id-swiper/lib/ReactIdSwiper.custom';
class CustomBuildSwiper extends React.Component {
constructor(props) {
super(props);
this.swiperRef = React.createRef();
}
getSwiper(instance) {
console.log(instance);
instance.on('slideChange', () => {
console.log(instance.activeIndex);
});
instance.on('reachEnd', () => {
console.log('end!');
});
}
render() {
const params = {
// Provide Swiper class as props
Swiper,
// Add modules you need
modules: [Navigation, Pagination],
pagination: {
el: '.swiper-pagination',
type: 'bullets',
clickable: true
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
},
spaceBetween: 30,
loop: true,
getSwiper: this.getSwiper
};
return (
<ReactIdSwiperCustom {...params}>
<div>Slide 1</div>
<div>Slide 2</div>
<div>Slide 3</div>
<div>Slide 4</div>
<div>Slide 5</div>
</ReactIdSwiperCustom>
);
}
}
Solution
So to solve this problem. I use the slideChange event only for loop mode.
For example:
I have 5 slides with the loop mode. The data can be visualized like this
5 1 2 3 4 5 1 // length: 7
As you can see to reach to the final slide. We have 2 ways
First is from 4 -> 5
We could check
if (prevSlide === n - 3 && currentSlide === n - 2) {
// do something here
}
Second is from 1 -> 5
if (prevSlide === 1 && currentSlide === 0) {
// do something here
}