Loop video with hover ReactJS

Viewed 493

I am trying to autoplay a video when rendered, but only once. On the hover effect, I would like it to play the video with a loop. I have tried to use event.target.play() on mouseOver but have had no luck.

Any help would be greatly appreciated :)

<video 
  className="videos" 
  autoPlay={true} 
  onMouseOver={event => event.target.play()} 
  onMouseOut={event => event.target.pause()} 
  muted={true}
  src={prompt}>
</video>

2 Answers

You can use onEnded event along with mouseover to loop it. Also using useRef makes it easy to set/play instead of passing event from all the callbacks. Check below code,

import { useEffect, useRef, useState } from "react";
import testVideo from "./testVideo.mp4";

export default function App() {
  const ref = useRef(null);
  const [focus, setFocus] = useState(false);

  const loop = () => {
    ref.current.play();
  };

  const onEndedLoop = () => {
    if (focus) loop(); // when ended check if its focused then loop
  };

  useEffect(() => {
    if (focus) loop(); // when focused then loop
  }, [focus]);

  return (
    <div className="App">
      <h2>Loop video with hover ReactJS!</h2>
      <video
        id="video"
        ref={ref}
        style={{ width: "300px" }}
        autoPlay
        onMouseOver={() => setFocus(true)}
        onMouseOut={() => setFocus(false)}
        muted={true}
        src={testVideo}
        onEnded={onEndedLoop}
      ></video>
    </div>
  );
}

check working demo - https://codesandbox.io/s/loop-video-on-hover-qegu7

@Madhuri has good answer (Which I upvoted). However, if we add a function to pause loop when not focused, that will loop the video only when in focus and stop when not hovering over or not in focus.

const loop = () => {
    ref.current.play();
  };

  const pauseLoop = () => {
    ref.current.pause();
  };

  const onEndedLoop = () => {
    if (focus) loop(); // when ended check if its focused then loop
  };

  useEffect(() => {
    if (focus) loop(); // when focused then loop
    if (!focus) pauseLoop(); // when not focused then pause loop
  }, [focus]);
Related