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 use ref hook and we use references to do things 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 here using these two buttons. To make this work, we just need to add an On Click to the play button and connect it to a new function such as Play video, which will create above our return and using ref dot current which is what is holding our video element here.

We can say ref dot current dot play to play the video, you can then add an On Click to our pause button connects it to a function pause video, copy our play video function, rename it to pause video, but this time say ref dot current dot pause and at this point, we can now play our video and pause it 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 US state we'll set the initial value to false and we'll call this bit of state is playing in the setter set playing. Remember I mentioned that you can add a couple of props on play which will determine when our video starts playing.

And when this callback is fired, we want to set the playing to true and there's also one on pause and we'll connect that to a function that sets the opposite boolean value and using the value in state is playing. We can add a ternary in that div or if it's playing we up with 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