How to add video support to React App

Adding videos to React app is always tricky and it becomes more complex when we need to mange different kind of formats like HTML5, Flash, Vimeo and Youtube videos. In this article we will gonna learn how to add videos support to React App.

Video.js

Video.js is a web video player built from the ground up for an HTML5 world. It supports HTML5 and Flash video, as well as YouTube and Vimeo (through plugins).

It supports video playback on desktops and mobile devices. This project was started mid 2010, and the player is now used on over 400,000 websites.

Installation

You can install this library using the npm.

npm i video.js --save

or you can use script tag as well.

<link href="//vjs.zencdn.net/7.8.2/video-js.min.css" rel="stylesheet">
<script src="//vjs.zencdn.net/7.8.2/video.min.js"></script>

Usage

First of all you need to import videojs function.

import videojs from "video.js";

Then we will gonna create options for our video compoent.

const videoJsOptions = {
  autoplay: false,
  playbackRates: [0.5, 1, 1.25, 1.5, 2],
  width: 720,
  height: 300,
  controls: true,
  sources: [
    {
      src: '//vjs.zencdn.net/v/oceans.mp4',
      type: 'video/mp4',
    },
  ],
};

We can simply provide these our options to our custom compoent.

<Videojs {...videoJsOptions} />

Our Videojs component will gonna look like this.

import React from 'react';
import videojs from 'video.js';

export default class VideoPlayer extends React.Component {
  componentDidMount() {
    // instantiate video.js
    this.player = videojs(this.videoNode, this.props, function onPlayerReady() {
      console.log('onPlayerReady', this);
    });
  }

  // destroy player on unmount// taken from https://github.com/videojs/video.js/blob/master/docs/guides/react.md
  componentWillUnmount() {
    if (this.player) {
      this.player.dispose();
    }
  }


  render() {
    return (
      <div data-vjs-player>
        <video ref={node => (this.videoNode = node)} className="video-js" />
      </div>
    );
  }
}

Just a normal video element with reference and on CDM we are passing our options object to our video element.

How to add video support to React App

Our output will gonna look like this.

Demo

It also supports a lot of customization using plugins.

I hope you have learned how to add video support to React App.

How to write regex in natural language


2 Comments

How to use Chrome DevTools Issues Tab - Blog React · August 5, 2020 at 3:50 am

[…] How to add video support to React App Categories: ChromeJavaScriptReactjs Tags: ChromeJavaScriptTools […]

How to write complex layouts in one line of Css - Blog React · August 7, 2020 at 3:45 am

[…] How to add video support to React App […]

Comments are closed.