Hey I was trying to make a Video player in react and wanted to make my own controls but I am facing an issue.the handlePlay is an OnClick function should play or pause the video. isPlaying is the state to keep track of users command(isPlaying is initialized to true) but even when the state is updated the video doesnt pause.Can somebody help
Thnx
class Video extends React.Component {
constructor(...args) {
super(...args);
const video = document.createElement("video");
video.src = Vid;
video.type = "video/mp4";
this.state = {
video: video,
timestamps: [],
isPlaying: true,
};
video.addEventListener("canplay", () => {
if (this.state.isPlaying === true) {
console.log("play");
video.play();
//this.image.getLayer().batchDraw();
// this.requestUpdate();
} else {
console.log("pause");
video.pause();
//this.image.getLayer().batchDraw();
//this.requestUpdate();
}
});
}
handlePlay = () => {
if (this.state.isPlaying === true) {
this.setState({
isPlaying: false,
});
} else {
this.setState({
isPlaying: true,
});
}
};
First you should use React component's render method for your video rendering and then hook the correct onClick handlers in order to play/pause with a custom control. The code would look something like this:
import React, { Component } from "react";
export default class Video extends Component {
constructor(props) {
super(props);
this.state = {
timestamps: [],
isPlaying: true
};
}
videoRef = React.createRef();
handlePlay = () => {
if (this.state.isPlaying === true) {
this.videoRef.current.pause();
this.setState({
isPlaying: false
});
} else {
this.videoRef.current.play();
this.setState({
isPlaying: true
});
}
};
render() {
return (
<>
<video
ref={this.videoRef}
autoPlay
src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
/>
<button type="button" onClick={this.handlePlay}>
Control
</button>
</>
);
}
}
I created a dummy button to emulate your control.
The videoRef is needed to keep the video element's reference which is assigned to it with the ref property and accessed as videoRef.current. You can learn more about refs in the official React docs.
You can find a working example on the following code sandbox.