Loading video...

Solution

Media Playback Solution

Create a dedicated ref using the useRef hook.

const ref = useRef();

After that, connect it to the video element:

<video ref={ref} />

After adding onClick to both of the buttons, you can play and pause the video by connecting them to the following functions, using the ref.

function playVideo() {
    ref.current.play();
}

function pauseVideo() {
    ref.current.pause();
}

Transcript

We learned how to get a reference with the useRef hook, and we use references to perform tasks outside of React when there isn't a React way to do something. We can connect a ref with a given element. In this case, we wanted to connect a ref with our video element.

So, we'll move the ref down to the video element. Using this ref, we want to play and pause the video using these two buttons. To make this work, we just need to add an onClick to the play button and connect it to a new function, such as playVideo, which we will create above our return statement. Using ref.current, which is what is holding our video element, we can say ref.current.play() to play the video. You can then add an onClick to our pause button, connect it to a function pauseVideo, copy our playVideo function, rename it to pauseVideo, but this time say ref.current.pause(). At this point, we can now play and pause our video, but we don't see the state here. We want to display whether it's playing or paused within this div between the two buttons.

We can manage this using plain state with useState. We'll set the initial value to false, and we'll call this piece of state isPlaying and the setter setPlaying. Remember, I mentioned that you can add a couple of props, onPlay, which will determine when our video starts playing.

And when this callback is fired, we want to set isPlaying to true. There's also onPause, and we'll connect that to a function that sets the opposite boolean value. Using the value in state isPlaying, we can add a ternary in that div: if it's playing, we display the text "Playing"; otherwise, the text "Paused".

Now our video player is fully functional: we can play, we see the text "Playing", and when we pause, we see the text "Paused".