How could I reset the position of a child swiper when changing slides in the parent swiper in a nested swiper setup? #8193
Replies: 1 comment
|
I reproduced this with your sandbox's components using Swiper 12.2.0 and React 18.2.0. You can handle this entirely inside Add these imports: import { useEffect, useRef } from "react";
import { Swiper, SwiperSlide, useSwiper } from "swiper/react";
import type { Swiper as SwiperInstance } from "swiper";Inside // HorseCard is inside the parent's SwiperSlide. This hook runs outside
// the child <Swiper> returned below, so it reads the parent instance.
const parentSwiper = useSwiper();
const childSwiperRef = useRef<SwiperInstance | null>(null);
useEffect(() => {
const resetInactiveChild = () => {
const child = childSwiperRef.current;
if (!child || child.destroyed || parentSwiper.destroyed) return;
const activeSlide = parentSwiper.slides[parentSwiper.activeIndex];
if (activeSlide && !activeSlide.contains(child.el)) {
child.slideTo(0, 0);
}
};
parentSwiper.on("slideChangeTransitionEnd", resetInactiveChild);
return () => {
parentSwiper.off("slideChangeTransitionEnd", resetInactiveChild);
};
}, [parentSwiper]);Then add this prop to your existing horizontal onSwiper={(swiper) => {
childSwiperRef.current = swiper;
}}Keep its existing slides and other props unchanged. No changes are needed in
I checked the original horizontal → vertical → return sequence with mouse drags in Chrome, plus forward/back navigation, zero-duration and rapid parent transitions, and remounting under React StrictMode. The fix does not recreate the child Swiper instances. This targets your current non-loop, non- References: useSwiper, slideTo, slideChangeTransitionEnd. |
Uh oh!
There was an error while loading. Please reload this page.
Context
Sandbox environment
I have a multiple horizontal swipers nested within a parent vertical swiper. The parent swiper lives within
src/components/HorseCardsContainer.tsxand children are modeled by the componentsrc/components/HorseCard.tsx.Problem
The horizontal child swipers maintain their position when swiping vertically, instead I'd like for the children to reset back to their first swiper slide after swiping vertically.
Problem demo
Question
How could I reset the children's swiper slide back to the initial slide after swiping vertically with the parent?
All reactions