I am using video.js in React. I try to migrate to React Hooks.
My React version is 16.8.3
This is original working code:
import React, { PureComponent } from 'react';
import videojs from 'video.js';
class VideoPlayer extends PureComponent {
componentDidMount() {
const { videoSrc } = this.props;
const { playerRef } = this.refs;
this.player = videojs(playerRef, { autoplay: true, muted: true }, () => {
this.player.src(videoSrc);
});
}
componentWillUnmount() {
if (this.player) this.player.dispose()
}
render() {
return (
<div data-vjs-player>
<video ref="playerRef" className="video-js vjs-16-9" playsInline />
</div>
);
}
}
After adding React Hooks
import React, { useEffect, useRef } from 'react';
import videojs from 'video.js';
function VideoPlayer(props) {
const { videoSrc } = props;
const playerRef = useRef();
useEffect(() => {
const player = videojs(playerRef.current, { autoplay: true, muted: true }, () => {
player.src(videoSrc);
});
return () => {
player.dispose();
};
});
return (
<div data-vjs-player>
<video ref="playerRef" className="video-js vjs-16-9" playsInline />
</div>
);
}
I got the error
Invariant Violation: Function components cannot have refs. Did you mean to use React.forwardRef()?
But I am using React Hooks useRef
instead of refs
actually. Any guide will be helpful.
To play video in React, you need to use the HTML video element, specify a source of the video and its type. Along with these required attributes, you can provide additional properties to customize the video player.
Redux and React Hooks should be seen as complements and also as different things. While with the new React Hooks additions, useContext and useReducer, you can manage the global state, in projects with larger complexity you can rely on Redux to help you manage the application data.
Don't call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders.
React hooks have been around for some time now, yet many React developers are not actively using them.
You are passing a string to the video element's ref
prop. Give it the playerRef
variable instead.
You can also give useEffect
an empty array as second argument as you only want to run the effect after the initial render.
function VideoPlayer(props) {
const { videoSrc } = props;
const playerRef = useRef();
useEffect(() => {
const player = videojs(playerRef.current, { autoplay: true, muted: true }, () => {
player.src(videoSrc);
});
return () => {
player.dispose();
};
}, []);
return (
<div data-vjs-player>
<video ref={playerRef} className="video-js vjs-16-9" playsInline />
</div>
);
}
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