Created
June 16, 2020 14:10
-
-
Save vazbloke/0cd11594df8c8c70dfa0ea8eb4fbca89 to your computer and use it in GitHub Desktop.
A Video JS component in React, using hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
import { useState, useEffect, useRef } from 'react'; | |
import videojs from 'video.js'; | |
import 'video.js/dist/video-js.min.css'; | |
interface PlayerProps { | |
src: string; | |
type: string; | |
} | |
const options = { | |
fill: true, | |
fluid: true, | |
responsive: true, | |
preload: 'auto', | |
controls: true, | |
}; | |
export const VideoPlayer = ({ src = '', type = 'video/mp4' }: PlayerProps) => { | |
const videoRef = useRef(null); | |
const [player, setPlayer] = useState(null); | |
useEffect(() => { | |
const vjsPlayer = videojs(videoRef.current, options); | |
setPlayer(vjsPlayer); | |
return () => vjsPlayer.dispose(); | |
}, []); | |
useEffect(() => { | |
if (player !== null) { | |
player.src({ src, type }); | |
} | |
}, [src, type, player]); | |
return ( | |
<div> | |
{/* eslint-disable-next-line jsx-a11y/media-has-caption */} | |
<video ref={videoRef} className="video-js"> | |
<p className="vjs-no-js"> | |
To view this video please enable JavaScript, and consider upgrading to | |
a web browser that | |
<a href="https://videojs.com/html5-video-support/"> | |
supports HTML5 video | |
</a> | |
</p> | |
</video> | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment