SwiperJS documentation states that navigation prevEl/nextEl can either be of type "string" or "HTMLElement". Using string selectors is easy enough as:
const MySwiper = (props) => (
<Swiper
navigation={{
prevEl: '.prev',
nextEl: '.next',
}}
{...props}
>
<SwiperSlide>slide 1</SwiperSlide>
<SwiperSlide>slide 2</SwiperSlide>
<div className="prev" />
<div className="next" />
</Swiper>
)
However, how would this be correctly implemented with React refs? Using HTML nodes instead of string selectors allows for navigation prevEl/nextEl to be scoped to each rendered instance of MySwiper
.
const App = () => (
<div>
<MySwiper className="mySwiper1" />
<MySwiper className="mySwiper2" />
</div>
)
In the App example above, navigation prevEl/nextEl from .mySwiper2
should not trigger sliding of .mySwiper1
, which is what would happen with string selectors.
My current sad & hacky workaround:
const MySwiper = () => {
const navigationPrevRef = React.useRef(null)
const navigationNextRef = React.useRef(null)
return (
<Swiper
navigation={{
// Both prevEl & nextEl are null at render so this does not work
prevEl: navigationPrevRef.current,
nextEl: navigationNextRef.current,
}}
onSwiper={(swiper) => {
// Delay execution for the refs to be defined
setTimeout(() => {
// Override prevEl & nextEl now that refs are defined
swiper.params.navigation.prevEl = navigationPrevRef.current
swiper.params.navigation.nextEl = navigationNextRef.current
// Re-init navigation
swiper.navigation.destroy()
swiper.navigation.init()
swiper.navigation.update()
})
}}
>
<SwiperSlide>slide 1</SwiperSlide>
<SwiperSlide>slide 2</SwiperSlide>
<div ref={navigationPrevRef} />
<div ref={navigationNextRef} />
</Swiper>
)
}