Reputation: 197
I am trying to learn swiper.js in react by building a simple image slider with autoplay and I don't know how to stop autoplay onMouseEnter and start it onMouseLeave. I tried onMouseLeave={Swiper.autoplay.stop} and it didn't work.
import React from 'react';
import classes from './HeroSlider.module.css';
import { Swiper, SwiperSlide } from 'swiper/react';
import SwiperCore, { Navigation, Pagination, Autoplay } from 'swiper';
import 'swiper/swiper-bundle.css'; // swiper.min.css
import image1 from '../../Images/image1.png';
import image2 from '../../Images/image2.png';
import image3 from '../../../Images/image3.png';
SwiperCore.use([ Navigation, Pagination, Autoplay ]);
const HeroSlider = () => {
return (
<Swiper
className={ classes.MainSlider }
autoplay={{ delay: 5000, disableOnInteraction: false, reverseDirection: true, waitForTransition: true }}
pagination={{ clickable: true }}
navigation
onMouseEnter={}
onMouseLeave={}
>
<SwiperSlide className="full-w-h-container" tag="li" style={{ listStyle: "none" }}>
<img className={ `full-w-h-container ${ classes.ImgBg }` } src={image1} alt="image1" />
</SwiperSlide>
<SwiperSlide className="full-w-h-container" tag="li" style={{ listStyle: "none" }}>
<img className={ `full-w-h-container ${ classes.ImgBg }` } src={image2} alt="image2" />
</SwiperSlide>
<SwiperSlide className="full-w-h-container" tag="li" style={{ listStyle: "none" }}>
<img className={ `full-w-h-container ${ classes.ImgBg }` } src={image3} alt="image3" />
</SwiperSlide>
</Swiper>
)
}
export default HeroSlider;
Edit:
I tried something like onMouseEnter={() => Swiper.autoplay.stop()} onMouseLeave={() => Swiper.autoplay.start()} but It doesn't work strangely though if I use something like: onClick={() => Swiper.autoplay.stop()} It works...
Upvotes: 4
Views: 7559
Reputation: 4769
You can also use pauseOnMouseEnter: true
:
autoplay={{
delay: 3000,
disableOnInteraction: false,
pauseOnMouseEnter: true,
}}
Upvotes: 5
Reputation: 96
At the time of writing this, it looks like Swiper for React doesn't implement onMouseEnter
, onMouseLeave
, etc.
To work around this, I wrapped my Swiper component in another React component and referenced Swiper with a reference like so:
import React, { useRef } from 'react'
import { Swiper, SwiperSlide } from 'swiper/react'
import SwiperCore, { Autoplay, Pagination } from 'swiper'
// ...
SwiperCore.use([Autoplay, Pagination])
export default function Slider() {
const swiperRef = useRef(null)
return (
<div
onMouseEnter={() => swiperRef.current.swiper.autoplay.stop()}
onMouseLeave={() => swiperRef.current.swiper.autoplay.start()}
>
<Swiper
ref={swiperRef}
autoplay={{ delay: 5000 }}
speed={1300}
spaceBetween={50}
slidesPerView={1}
allowTouchMove={false}
pagination={{ clickable: true }}
>
{/* slides */}
</Swiper>
</div>
)
}
Upvotes: 8