The video still plays in the background (sound) even after the video player has been closed. I tried using pause() but apparently it isn’t a function. If I select another thumbnail and bring up another video the current one will stop. I’m thinking of doing that in the background if I cannot get his to work but I prefer my code to be elegant and simple.
import './stylesheets/VideoPlayer.css';
import ExitButton from './ExitButton';
import ReactPlayer from 'react-player';
///-----------
import React, { useRef, useState } from 'react';
///-----------
function VideoPlayer(props) {
///-------------
const [isPlayerVisible, setPlayerVisibility] = useState(false);
const playerRef = useRef(null); // Create a ref using useRef
///-------------
const handleExit = () => {
const player = document.getElementById('VideoPlayer') || document.getElementById('VideoPlayer-Active');
if (player) {
player.id = player.id === 'VideoPlayer' ? 'VideoPlayer-Active' : 'VideoPlayer';
} else {
console.log('error, no video player');
}
///----------------
if (playerRef.current) {
// playerRef.current.seekTo(0); // Seek to the beginning
// playerRef.current.pause(); // Pause the video -- NOT working
playerRef.current.playing = false;
// console.log(playerRef.current);
} else {
console.log('not current');
}
setPlayerVisibility(false);
///----------------
}
///---------------
const handlePlay = () => {
setPlayerVisibility(true);
};
///---------------
return (
<div id="VideoPlayer">
<ExitButton onExit={handleExit} />
<ReactPlayer
ref={playerRef}
url={props.nowPlaying.videoUrl}
controls={true}
width="100%"
height="100%"
///----------------
onPlay={handlePlay}
///----------------
/>
</div>
);
}
export default VideoPlayer;
2
Answers
So apparently I just needed to define my own pause function. Thanks for trying, SO
Direct change of the
playing
property for sure won’t change anything since it’s just a field mutation, you should seek for an instance method (a function) that stops the player.Based on the docs located here, to stop the video you need to pass
playing
prop to theReactPlayer
component.