swiper instance: Cannot read properties of undefined (reading 'slideChange') with React 18
See original GitHub issueCheck that this is really a bug
- I confirm
Reproduction link
upd: https://github.com/b-novikov-ipersonality/swiper-react18-bug
Bug description
After initializing swiper instance by passing <Swiper>
component setState
function, when using any of the swiper instance events, for example
swiper.on('slideChange', (swiper) => ...)
or any other, I get runtime error: TypeError: Cannot read properties of undefined (reading 'activeIndexChange')
error img
Note that Swiper has many problems with React 18, among them #5613 #5630 #5609 so it’s probably some form of incompatibility with react 18. Maybe until the fix is released you should make Swiper require react <18.0.0?
Steps to reproduce:
- create new react app
- paste following code into component
export default function Home() {
const [swiper, setSwiper] = useState(null);
const [currentSlide, setCurrentSlide] = useState(0);
useEffect(() => {
if (swiper) {
swiper.on('activeIndexChange', (swiper) => {
setCurrentSlide(swiper.realIndex);
})
}
}, [swiper])
return (
<>
<h1>CURRENT SLIDE: {currentSlide}</h1>
<Swiper draggable className={styles.swiper} onSwiper={setSwiper}>
<SwiperSlide>1</SwiperSlide>
<SwiperSlide>2</SwiperSlide>
<SwiperSlide>3</SwiperSlide>
<SwiperSlide>4</SwiperSlide>
<SwiperSlide>5</SwiperSlide>
</Swiper>
</>
);
}
- use component somewhere in your app
- experience error and sorrow
Expected Behavior
I can use event listeners on swiper instances without error
Actual Behavior
When using event listeners on swiper instance error TypeError: Cannot read properties of undefined (reading 'event_name')
occur where event_name
is the name of the used event
Swiper version
“^8.1.1”
Platform/Target and Browser Versions
linux, chrome Version 100.0.4896.88 (Official Build) (64-bit)
Validations
- Follow our Code of Conduct
- Read the docs.
- Check that there isn’t already an issue that request the same feature to avoid creating a duplicate.
- Make sure this is a Swiper issue and not a framework-specific issue
Would you like to open a PR for this bug?
- I’m willing to open a PR
Issue Analytics
- State:
- Created a year ago
- Comments:7 (2 by maintainers)
@vandreleal hey. It was fixed by @nolimits4web. If it still does not work for you, the workaround was provided by @MaksimAmelchenko:
@nolimits4web, problem is only reproducible with Strict mode enabled. But in my opinion removing strict mode shouldn’t be a permanent solution because strict mode helps here and there in development.