How to play / pause video in Response without an external library?

I have a video tag () on my web page and a play / pause button that, when a user clicks on it, starts / stops video playback. How can I do this in response if I am not allowed to use js to call "getElementById" and then use the built-in play () / pause () methods. Any ideas?

+8
source share
2 answers

The easiest way is to use refs which are a React function that will allow you to call methods on instances of components that you returned from render() .

You can read a little more about them in the documentation: https://facebook.imtqy.com/react/docs/more-about-refs.html

In this case, just add ref to your video tag as follows:

 <video ref="vidRef" src="some.mp4" type="video/mp4"></video> 

Thus, when you add click handlers to your buttons:

 <button onClick={this.playVideo.bind(this)}>PLAY</button> 

The playVideo method will have access to your video link through refs :

 playVideo() { this.refs.vidRef.play(); } 

Here is a working DEMO, so you can see a complete example.

+11
source

The accepted answer used the old reaction style if you want to use ES6

A simple component for automatic pause playback along with manual control of Polestar intro playback:

  import React from "react"; class Video extends React.Component { componentDidMount = () => { this.playVideo(); }; componentWillUnmount = () => { this.pauseVideo(); }; playVideo = () => { // You can use the play method as normal on your video ref this.refs.vidRef.play(); }; pauseVideo = () => { // Pause as well this.refs.vidRef.pause(); }; render = () => { return ( <div> <video ref="vidRef" src="https://assets.polestar.com/video/test/polestar-1_09.mp4" type="video/mp4" /> <div> <button onClick={this.playVideo}> Play! </button> <button onClick={this.pauseVideo}> Pause! </button> </div> </div> ); }; } export default Video; 

Video from https://www.polestar.com/cars/polestar-1

0
source

All Articles