카테고리 없음

리액트 스크롤 비디오 자동재생

Mori_FEDev 2023. 4. 17. 15:15

리액트에서 스크롤 여부에 따라서 video가 자동재생 되도록 해야 했다.

나는 scrollevent를 사용해 autoplay속성을 setAttruibute로 적용해봤으나,

코드에는 autoplay속성이 들어갔는데 정작 재생이 안됬다.

 

스택오버플로와 코드박스를 참고하여 해결했다.

import React, { useEffect, useRef } from "react";
import "./styles.css";

const App = () => {
  const videoRef = useRef(null);

  useEffect(() => {
    let options = {
      rootMargin: "0px",
      threshold: [0.25, 0.75]
    };

    let handlePlay = (entries, observer) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          videoRef.current.play();
        } else {
          videoRef.current.pause();
        }
      });
    };

    let observer = new IntersectionObserver(handlePlay, options);

    observer.observe(videoRef.current);
  });

  return (
    <div className="App">
      <h1>Scroll Down</h1>
      <div className="container">
        <div className="video-container">
          <video
            ref={videoRef}
            src="https://archive.org/download/BigBuckBunny_124/Content/big_buck_bunny_720p_surround.mp4"
          ></video>
        </div>
      </div>
      <h2>That's All Folks!</h2>
    </div>
  );
};

export default App;

 

 

 

코드샌드박스 : 

https://codesandbox.io/s/strange-smoke-p9hmx

 

strange-smoke-p9hmx - CodeSandbox

strange-smoke-p9hmx by abelmark using react, react-dom, react-scripts

codesandbox.io

https://stackoverflow.com/questions/63890401/play-pause-video-onscroll-in-reactjs/63890777#63890777

 

 

Play/Pause video onScroll in Reactjs

I'm trying to achieve a functionality where on scrolling a video gets paused if it was playing and vice versa. Currently I can do it with an onClick function that sets the state true/false. But the

stackoverflow.com