The documentation for the react-youtube library is very scarce and I'm trying to reference the player to use the pauseVideo() and playVideo() functions when an external value changes. In the official youtube api docs they put the player in a var and reference that but the react-youtube docs only explain that the player is passed as the target value for an event. So what do I use to reference the player and use it's functionality without an event?

This is for a chat room type application with a synchronized video player, below is the code for the video player function. Included within it is a text field to put a URL and a button to submit it to the room. I am currently successfully broadcasting to the room the new state of the player when it changes and I would like to change the state of the players for each user in the room when that happens, but to do so I need to reference the player, which again I'm having trouble with.

import YouTube from "react-youtube"; function SyncPlayer({ code, setPlayerURL, sendCode, onPlayerStateChange, playerState} ) { useEffect(() => { if(playerState == 1){ youtubePlayer.playVideo();//not valid reference to player } }, [playerState]) const opts = { playerVars: { autoplay: 0 } }; return ( <div> <div> <input type="text" placeholder="Video URL" onChange={(event) => setPlayerURL(event.target.value)}/> <button onClick={(event) => sendCode(event)}>submit</button> <div> <YouTube videoId={code} containerClassName="embed embed-youtube" opts={opts} onStateChange={onPlayerStateChange} /> </div> </div> </div> ); } export default SyncPlayer; 

1 Answer

Ok looks like I figured it out.

So the onReady function of the player stores the event passed in a global variable and I use that to reference the player. Here is what that looks like:

import YouTube from "react-youtube"; var cElement = null; function SyncPlayer({ code, setPlayerURL, sendCode, onPlayerStateChange, playerState} ) { useEffect(() => { if(cElement){ var player = cElement.target; if(playerState === 1){ player.playVideo(); } if(playerState === 2){ player.pauseVideo(); } } }, [playerState]); const storeEvent = event =>{ cElement = event; }; const opts = { playerVars: { autoplay: 0 } }; return ( <div> <div> <input type="text" placeholder="Video URL" onChange={(event) => setPlayerURL(event.target.value)}/> <button onClick={(event) => sendCode(event)}>submit</button> <div> <YouTube videoId={code} containerClassName="embed embed-youtube" opts={opts} onStateChange={onPlayerStateChange} onReady={storeEvent} /> </div> </div> </div> ); } export default SyncPlayer; 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy