How to refresh video.js player for new video
I'm using video.js as a video player, but I am facing a problem. The problem is that when I'm trying to play any other video, the player does not refresh and it always plays the old video.
import React, { Component } from 'react';
import videojs from 'video.js';
import { sendData } from '../../analytics/sendData';
class Video360Player extends Component {
componentDidMount() {
// instantiate Video.js
const videoJsOptions = {
autoplay: true,
controls: true,
sources: [{
src: this.props.videoUrl,
type: 'video/mp4'
}]
}
this.player = videojs(this.videoNode, videoJsOptions,this.props, function onPlayerReady() {
console.log('onPlayerReady', this)
});
}
// destroy player on unmount
componentWillUnmount() {
if (this.player) {
this.player.dispose()
}
}
// wrap the player in a div with a `data-vjs-player` attribute
// so videojs won't create additional wrapper in the DOM
// see https://github.com/videojs/video.js/pull/3856
render() {
return (
<div>
<div data-vjs-player>
<video ref={ node => this.videoNode = node } className="video-js"></video>
</div>
</div>
)
}}
export default Video360Player
It happens because your Video360Player
has player
and you pass videoJsOptions
to that player
in the componentDidUpdate
which invoke only once while component is mounted. So to fix that you should add componentWillReceiveProps
:
componentWillReceiveProps(nextProps) {
if (nextProps.videoUrl !== this.props.videoUrl) {
this.player.dispose();
const videoJsOptions = {
autoplay: true,
controls: true,
sources: [
{
src: this.props.videoUrl,
type: "video/mp4",
},
],
};
this.player = videojs(
this.videoNode,
videoJsOptions,
this.props,
function onPlayerReady() {
console.log("onPlayerReady", this);
}
);
}
}