Skip to content

Instantly share code, notes, and snippets.

@ryanmcgrath
Last active January 23, 2021 09:42
Show Gist options
  • Save ryanmcgrath/9e9757aa429b1684c9d0 to your computer and use it in GitHub Desktop.
Save ryanmcgrath/9e9757aa429b1684c9d0 to your computer and use it in GitHub Desktop.
A basic React Video tag. I wanted to use video.js inside something I was building, so this is more or less a 5-minute tag for handling it. ES6 syntax but you can extrapolate what you need. Handles dynamically loading video.js/css as necessary since I really loathe serving any swf/etc myself. Could be easily extended or made better, works for me …
import React from 'react';
import Video from './Video';
class MyGenericApp extends React.Component {
render() {
return <div>
<Video src="my_video_url" poster="my_poster_url" />
</div>;
}
}
import $ from 'jquery';
import React from 'react';
export default class Video extends React.Component {
static defaultProps = {
poster: null,
src: null,
width: 640,
height: 360,
className: 'video-js vjs-default-skin vjs-big-play-centered',
controls: true,
autoplay: false,
preload: 'auto',
}
componentDidMount() { this.checkIfVideoNeedsInstallation(); }
componentDidUpdate() { this.checkIfVideoNeedsInstallation(); }
checkIfVideoNeedsInstallation = () => {
if(!this.props.src)
return;
if(typeof videojs === 'undefined') {
$('<link/>', {rel: 'stylesheet', type: 'text/css', href: 'https://vjs.zencdn.net/4.12/video-js.css'}).appendTo('head');
$.getScript('https://vjs.zencdn.net/4.12/video.js', this.loadVideo);
} else {
this.loadVideo();
}
}
loadVideo = () => {
if(this.video || !this.props.src)
return;
let node = React.findDOMNode(this.refs.videoplayer);
if(!node)
return;
this.video = document.createElement('video');
this.video.src = this.props.src;
this.video.width = this.props.width;
this.video.height = this.props.height;
this.video.className = this.props.className;
node.appendChild(this.video);
videojs(this.video, this.props);
}
render() {
return <div ref="videoplayer" />;
}
}
@apurvgandhwani
Copy link

I have few questions

  1. From where the function "componentDidMount() " getting called?
  2. What is videojs in this line(23) "if(typeof videojs === 'undefined')"
  3. Why did we give 'video' as the argument in the line(36) "this.video = document.createElement('video');

@BernardoFBBraga
Copy link

BernardoFBBraga commented Nov 21, 2016

@ryanmcgrath videojs is undefined, is something missing here?

should I npm install --save-dev video.js and import videojs from 'video.js'?

@OlafSzmidt
Copy link

@apurvgandhwani To answer question 1, you need to read the documentation of react. You don't call it explicitly. To answer question 3, that's just how HTML works. Video argument will create a video element and place it in this instance, calling the variable "video".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment