I have a video on my site that I want to be paused when I scroll it and play only when its visible. I have tried some solutions from internet but things are not working out. This is my current code. I have tried out a solution from stackoverflow which shows me observe error. I would be glad if someone helps me out on this. Thank you.
Player.js
import { Box, Container } from "@mui/system";
import React, { useEffect, useRef, useState } from "react";
import ReactPlayer from "react-player";
import styled from "styled-components";
import videosample from "./homepagevideo.mp4";
const ResponsiveStyledPlayer = () => {
const Player = ({ className }) => (
<ReactPlayer
url={videosample}
className={className}
playing={true}
autoplay={true}
width="100%"
height="100%"
controls={false}
muted
loop={true}]
/>
);
const AbsolutelyPositionedPlayer = styled(Player)`
position: absolute;
top: 0;
left: 0;
`;
const RelativePositionWrapper = styled.div`
position: relative;
padding-top: 56.25%;
`;
return (
<Box>
<Container>
<RelativePositionWrapper>
<AbsolutelyPositionedPlayer />
</RelativePositionWrapper>
</Container>
</Box>
)
};
export default ResponsiveStyledPlayer;
you can you Waypoint for your requirement. I have made one demo for you, you can refer to that. Link Demo
import React, { useState } from 'react';
import ReactPlayer from 'react-player/youtube';
import { Waypoint } from 'react-waypoint';
import './style.css';
export default function App() {
let [shouldPlay, updatePlayState] = useState(false);
let handleEnterViewport = function () {
updatePlayState(true);
};
let handleExitViewport = function () {
updatePlayState(false);
};
return (
<div>
<Waypoint onEnter={handleEnterViewport} onLeave={handleExitViewport}>
<div>
<ReactPlayer
playing={shouldPlay}
url="https://www.youtube.com/watch?v=ysz5S6PUM-U"
/>
</div>
</Waypoint>
<h1>hii</h1>
<br />
<h1>hii</h1>
<br />
<h1>hii</h1>
<br />
<h1>hii</h1>
<br />
<h1>hii</h1>
<br />
<h1>hii</h1>
<br />
<h1>hii</h1>
<br />
<h1>hii</h1>
<br />
<h1>hii</h1>
<br />
</div>
);
}