Click here to Skip to main content
15,883,792 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I got a child component called Video in my web app with a separate scrollbar enabled inside, where a list of video loads each taking the full height and width of the Video component. I need to trigger a pause of the current playing video when the user scrolls down to the next video and the next video should start playing immediately. And this should continue throughout the component. I'm using Intersection Observer API inside useEffect() but unable to achieve the functionality till now. My current function starts playing the videos on the list all at once. Is there any other way to achieve the feature? If not where am I going wrong??


What I have tried:

import React, { useRef, useState, useEffect } from "react";
import "./Video.css";
import VideoFooter from "./VideoFooter";
import VideoSidebar from "./VideoSidebar";

function Video({ url, likes, shares, messages, channel, description, song }) {

  const [playing, setPlaying] = useState(false);
  const videoRef = useRef(null);
                                      //NEED HELP OVER HERE
    useEffect(() => {
    let video = document.querySelector("video");
    let observer = new IntersectionObserver(
      (entry) => {
        if (entry.intersectionRatio != 0.5 && !playing) {
          videoRef.current.pause();
          setPlaying(true);
        } else if (playing) {
          videoRef.current.play();
          setPlaying(false);
        }
      },
      { threshold: 1 }
    );
    observer.observe(video);
  }, [playing]);

  const handleVideoPress = () => {
    if (playing) {
      videoRef.current.pause();
      setPlaying(false);
    } else {
      videoRef.current.play();
      setPlaying(true);
    }
  };

  return (
    <div className="video">
      <video
        onClick={handleVideoPress}
        className="video__player"
        loop
        ref={videoRef}
        src={url}
      ></video>
    </div>
  );
}

export default Video;
Posted

 
Share this answer
 
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900