Reputation: 4769
I am using Swiper js for my carousel and React and Typescript.
Following this post, I am trying to stop()
and start()
autoplay on hover. I need this approach because I have to create some states when hovering the Swiper container.
1) I get a typescript error the ref
property on my <Swiper ref={swiperRef}>
component:
Property 'ref' does not exist on type 'IntrinsicAttributes & Swiper & { children?
2) how do I get acces to swiper, so I can use swiper.autoplay.stop();
inside my handleMouseEnter
function? So I can use like:
const handleMouseEnter = () => {
swiper.autoplay.stop();
};
or like:
const handleMouseEnter = () => {
swiperRef.current.swiper.autoplay.stop();
};
This is the sandbox what I have so far.
How do I get this to work using Typescript?
Upvotes: 1
Views: 3659
Reputation: 93
you can store your swiper when it is initialized in a ref then use its controllerEvents like so:
import React from "react";
import { Swiper, SwiperSlide } from "swiper/react";
import SwiperCore, { Autoplay, Pagination } from "swiper";
SwiperCore.use([Pagination, Autoplay]);
export default function SwiperComponent() {
const swiperRef = React.useRef<SwiperCore>();
const onInit = (Swiper: SwiperCore): void => {
swiperRef.current = Swiper;
};
const handleMouseEnter = () => {
if (swiperRef.current) swiperRef.current.autoplay.start();
};
const handleMouseLeave = () => {
if (swiperRef.current) swiperRef.current.autoplay.stop();
};
return (
<div onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}>
<Swiper onInit={onInit}>
<SwiperSlide></SwiperSlide>
</Swiper>
</div>
);
}
Upvotes: 5