I am using react-slick for slider. I want to stop the video when the slide changes. I use useRef for this, but the play or pause functions do not work. How can i solve this?
import React, { useRef } from "react";
import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import "./styles.css";
export default function App() {
const videoRef = useRef<HTMLVideoElement>(null);
const slideAfterChange = (current: number) => {
console.log("after change", current);
console.log("video ref", videoRef);
videoRef.current?.pause();
};
const sliderSettings = {
dots: true,
infinite: true,
autoplay: true,
autoplaySpeed: 3000,
speed: 1000,
slidesToShow: 1,
slidesToScroll: 1,
afterChange: (currentSlide: number) => slideAfterChange(currentSlide)
};
return (
<div className="App">
<h1>Slider</h1>
<Slider {...sliderSettings}>
<div>
<video ref={videoRef} controls width="100%" height="100%">
<source
src={
"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"
}
></source>
</video>
</div>
<div>
<img src="http://placekitten.com/g/400/200" />
</div>
</Slider>
</div>
);
}
you can see on codesandbox https://codesandbox.io/s/reverent-swirles-m6bw1?file=/src/App.tsx
Instead of useRef you can add an id to the video player and then use getElementById.
const slideAfterChange = () => {
document.getElementById("videoPlayer")?.pause();
};
...
<video id="videoPlayer" controls width="100%" height="100%">