Integrate video.js player with React JS application
this article will help you in integrating the most popular javascript video player library video.js with React js application.
First create and run a React js application using create-react-app.
npx create-react-app video-js-app
cd video-js-app
npm start
Application server will start and runs on port 3000. Go to http://localhost:3000/ . You should able to see the below content in your web browser.
Next let us add video.js as a dependency to our project by running then following command.
npm i video.js
Now we have the video.js files copied to our project source code (Copied to node_modules).
Next let us create a folder with name video-js inside src folder of the app. Let us create a class component ( We can use either class or functional component here) inside the video-js folder as VideoJsComponent.
To style our player let us add bootstrap & video.js style files ( To keep the things simple let us make use of CDN’s ).
Add following code inside public/index.html file.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/video.js/7.0.0/video-js.min.css" integrity="sha512-zki7IiwYvLzVZouKA+V/vtIuW7cK8M2ug1kaRBItuBWG8TDvA6jrtjhKPOrz3RFGpt9OQC/xE7DUfsrHxoBXxg==" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" />
Next let’s write some videojs player code inside src/video-js/videojs.jsx file.
Copy & Paste the following code inside videojs.jsx file.
import React, {Component} from 'react';
import './videojs.css';
import videojs from 'video.js';
class VideoJSPlayerComponent extends Component {
player;
videoNode;
videoJsOptions = {
autoplay: true,
muted: true,
height: 400,
width: 600,
controls: true,
sources: [
{
src: "https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4",
type: "video/mp4"
}
],
};
constructor(props) {
super(props);
this.state = {
isPlaying: false,
playedSeconds: 0,
remainingVideoPlay: 0,
totalDuration: 0
};
}
componentDidMount() {
this.player = videojs(this.videoNode, this.videoJsOptions, () => {
if (this.player) {
// Triggered
console.log('onPlayerReady');
this.player.on('play', (event) => {
this.setState({
isPlaying: true,
})
})
this.player.on('loadedmetadata', (event) => {
// @ts-ignore
this.setState({totalDuration: this.player.duration()})
})
this.player.on('pause', (event) => {
this.setState({
isPlaying: false,
})
})
this.player.on('ended', (event) => {
console.log("ended")
})
this.player.on('timeupdate', (event) => {
// @ts-ignore
this.setState({playedSeconds: this.player.currentTime()})
// @ts-ignore
this.setState({remainingVideoPlay: this.player.remainingTime()})
})
}
});
}
play = () => {
if (this.player) {
this.player.play();
}
}
pause = () => {
if (this.player) {
this.player.pause();
}
}
forwardVideo = () => {
if (this.player) {
this.player.currentTime(this.player.currentTime() + 10);
}
}
backwardVideo = () => {
if (this.player) {
this.player.currentTime(this.player.currentTime() - 10);
}
}
jumpTo = () => {
if (this.player) {
this.player.currentTime(55);
}
}
togglePlay = () => {
if (this.state.isPlaying) {
this.pause();
} else {
this.play();
}
}
// destroy player on unmount
componentWillUnmount() {
if (this.player) {
this.player.dispose();
}
}
secondsToHms = (secs) => {
let hours = Math.floor(secs / 3600);
let minutes = Math.floor(secs / 60) % 60;
let seconds = Math.floor(secs % 60);
return [hours, minutes, seconds]
.map(v => v < 10 ? "0" + v : v)
.filter((v, i) => v !== "00" || i > 0)
.join(":")
};
render() {
const {totalDuration, playedSeconds, remainingVideoPlay, isPlaying} = this.state;
return (
<div className="customVideoPlayer">
<div className="playerWrapper" data-vjs-player>
<video id='video' ref={node => (this.videoNode = node)} className="video-js"/>
</div>
<hr/>
<div>
<div>
Played Time: {this.secondsToHms(playedSeconds)}
</div>
<div>
Total Time: {this.secondsToHms(totalDuration)}
</div>
<div>
Remaining Time: {this.secondsToHms(remainingVideoPlay)}
</div>
</div>
<br/>
<div className="d-flex">
<button className="btn btn-danger btn-sm" onClick={this.togglePlay}>{isPlaying ? "Pause" : "Play"}</button>
<button className="btn btn-danger btn-sm" onClick={this.jumpTo}>Play from 55th second</button>
<button className="btn btn-danger btn-sm" onClick={this.forwardVideo}>10 secs +</button>
<button className="btn btn-danger btn-sm" onClick={this.backwardVideo}>10 secs -</button>
</div>
</div>
);
}
}
export default VideoJSPlayerComponent;
Explanation
First we are importing videojs from video.js.
Next on ComponentDidMount life cycle method we are creating an instance for videojs by passing
1. the id attached to our video tag inside render method. ( id’s must match ).
2. configuration object to configure our player.
3. call back function to be called on player ready event( Perfect place to add event listeners to our video player ).
Let’s style our player bit . Copy and paste following code into src/video-js/videojs.css file.
.playerWrapper{
height: 100%;
width: 100%;
}
.customVideoPlayer{
padding-top: 100px;
color: black;
display: flex;
align-items: center;
flex-direction: column;
}
Next import and use our VideoJSPlayerComponent inside App.js file like below.
import './App.css';
import VideoJSPlayerComponent from "./Videojs/videojs";
function App() {
return (
<div className="App">
<VideoJSPlayerComponent/>
</div>
);
}
export default App;
That’s it folks. Now we are all set to play with the video.js player inside our React js app🎉🎉🎉.
Refer video.js documentation for more info.
Please find the source code at https://github.com/manojvarmaboppisetti/video-js-app.
Hope you find this article helpful. Please leave a clap if you learnt something. Feel free to post your questions. Happy Coding…!