I have a video tag () in my webpage, and a "play/pause" button that when the user clicks on it, the video starts/stops playing . How can I do so in react if I'm not allowed to use js in order to call "getElementById" and then to use play()/pause() build-in methods. Any idea?
The handler function is a toggler; enabling one to play or pause according to its current state. One can create a play button overlay style through the class video__play-button , whilst the same handler hides it through the class is-playing .
You could store all player instances in a Context and use a Provider and Consumer to pause all players if one starts playing. Since you pass a playing boolean to ReactPlayer, you can easily store a id or reference of the current playing player.
Take the reference of the audio file in ReactJS Using Audio Class. Set the default state of the song as not playing. Make a function to handle the Play/Pause of the song. Use the play() and pause() functions of audio class to do these operations.
Updated example for React Function Components:
import React, { useRef} from 'react'
function myComponent(props) {
const vidRef = useRef(null);
const handlePlayVideo = () => {
vidRef.current.play();
}
return (
<video ref={vidRef}>
<source src={[YOUR_SOURCE]} type="video/mp4" />
</video>
)
}
The most straightforward way would be to use refs
which is a React feature that will let you invoke methods on the component instances that you have returned from a render()
.
You can read up a little more on them in the docs: https://facebook.github.io/react/docs/more-about-refs.html
In this case just add a ref
string to your video
tag like so:
<video ref="vidRef" src="some.mp4" type="video/mp4"></video>
That way 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 reference through refs
:
playVideo() {
this.refs.vidRef.play();
}
Here is a working DEMO so you can check out a full example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With