Top 5 React Video Player Libraries For Rendering Videos

Top 5 React Video Player Libraries For Rendering Videos

React is a popular JavaScript library for building user interfaces, and it can be an excellent tool for creating interactive and engaging applications. One common use case for React is rendering videos, and there are many libraries available that can help you do this quickly and efficiently. This blog post will look at some of the top React video player libraries for rendering videos.

Vidstack.io

The first point in the blog post discussed Vidstack.io, which is a powerful and feature-rich video player library for React. Vidstack.io allows you to embed videos easily from various sources, including YouTube, Vimeo, and more, and provides several customization options to help you create a unique and engaging user experience. To use Vidstack.io in your React application, you will first need to install it using npm:

npm i lit @vidstack/player@next @vidstack/player-react@nextCode language: JavaScript (javascript)

Once you have installed Vidstack.io, you can import it into your React component and use it to render a video. For example:

import {Media, Video } from '@vidstack/player-react';

export function VidStack() {
  return (
    <Media>
  <Video loading="visible" poster="https://media-files.vidstack.io/poster.png" controls preload="true">
    <video loading="visible" poster="https://media-files.vidstack.io/poster-seo.png" src="https://media-files.vidstack.io/720p.mp4" preload="none" data-video="0" controls />
  </Video>
</Media>
  );
}Code language: JavaScript (javascript)

In this example, we use the Media and the Video component from Vidstack.io to render a video from YouTube. The src attribute specifies the URL of the video. There are two poster attributes, one defined in the Video component, which will be shown to the user, and another is used in the video element, which will be temporarily shown while loading the main poster or for SEO. The controls prop enables the default playback controls, allowing the user to play, pause, seek, and adjust the volume of the video.

You can also customize the player by using Tailwind CSS classes. For example, you can change the color of the controls or add a custom poster image to be displayed before the video starts. For a complete list of available props and descriptions, please refer to the Vidstack.io documentation.

Getting Started: Styling – Custom (React) | Vidstack

You can check out the code here: VidStack (codedamn.com)

Video.js

The second point in the blog post discussed Video.js, which is a popular open-source library for rendering videos in React applications. Video.js provides a consistent, easy-to-use API for working with HTML5 video and offers several useful features, such as support for multiple video formats, customizable controls, and the ability to add captions and subtitles. First, you need to install the VideoJS library and the VideoJS stylesheet by running the following command in your terminal:

npm install video.jsCode language: JavaScript (javascript)
npm install video.js/dist/video-js.cssCode language: JavaScript (javascript)

Once the library and stylesheet are installed, you can import the VideoJS component into your application and use it to display a video player. Here’s an example of how you can do this:

import React from 'react';
import VideoJS from './VideoJS';

const VideoJS = (props) => {

  );
    />
  );
};

export default VideoJS;Code language: JavaScript (javascript)

The above code has a functional component called VideoJS that renders a Video.js player in a React application.

import React, { useEffect, useRef } from 'react';Code language: JavaScript (javascript)

The component makes use of the useEffect and useRef hooks from React to manage the lifecycle of the Video.js player.

    const refVideo = useRef(null);
  const refPlayer = useRef(null);
  const {options, onReady} = props;Code language: JavaScript (javascript)

At the beginning of the component, before the return statement, using useRef, initialize a const variable called refVideo that is used to store a reference to the div element containing the Video.js player. We also have another ref called refPlayer that will be used to store a reference to the Video.js player instance.

The component takes in two props: options and onReadyOptions is an object containing configuration options for the Video.js player, such as the sources for the video and whether the player should autoplay. onReady is a callback function that will be called when the Video.js player is ready.

useEffect(() => {

    // Make sure Video.js player is only initialized once
    if (!refPlayer.current) {
      // The Video.js player needs to be _inside_ the component el for React 18 Strict Mode. 
      const videoElement = document.createElement("video-js");

      videoElement.classList.add('vjs-big-play-centered');
      refVideo.current.appendChild(videoElement);

      const player = refPlayer.current = videojs(videoElement, options, () => {
        videojs.log('player is ready');
        onReady && onReady(player);
      });

    // You could update an existing player in the `else` block here
    // on prop change, for example:
    } else {
      const player = refPlayer.current;

      player.autoplay(options.autoplay);
      player.src(options.sources);
    }
  }, [options, refVideo]);Code language: JavaScript (javascript)

After the variables, add the useEffect hook responsible for initializing the Video.js player. Inside the hook, we first check if refPlayer.current is null, which means that the player has not been initialized yet. If that is the case, we create a new video-js element, append it to the div element stored in refVideo, and then initialize a new Video.js player with the videojs function, passing in the video-js element, the options prop and a callback function as arguments. This callback function passed to onReady, will be called when the player is ready.

If refPlayer.current is not null, it means that the player has already been initialized and we can update it with new options. In the code, this is done by setting the player’s autoplay and source options to the corresponding values from the options prop.

useEffect(() => {
    const player = refPlayer.current;

    return () => {
      if (player && !player.isDisposed()) {
        player.dispose();
        refPlayer.current = null;
      }
    };
  }, [refPlayer]);Code language: JavaScript (javascript)

The second useEffect hook cleans up the Video.js player when the component unmounts. Inside the hook, we check if refPlayer.current is not null, which means that the player has been initialized. If that is the case, we call the player’s dispose method to properly clean up the player and set refPlayer.current to null.

Finally, the component returns a div element with the data-vjs-player attribute and a div element inside it, which is the element that will contain the Video.js player. This outer div element is needed for Video.js to work correctly with React.

Overall, the VideoJS component allows us to easily embed a Video.js player in a React application, taking care of the player’s initialization, updates, and cleanup.

Now in the App component, import the VideoJS component.

import VideoJS from './VideoJS'Code language: JavaScript (javascript)

Create a variable called refPlayer that uses the useRef hook. This ref will store a reference to the video.js player instance, which will be passed to the VideoJS component through the onReady prop.

const refPlayer = useRef(null);Code language: JavaScript (javascript)

The App component also defines a videoJsOptions object that specifies the options for the video.js player. These options include whether the player should start playing automatically (autoplay), whether it should show controls (controls), whether it should be responsive to the size of its container (responsive), and whether it should take up all the available space in its container (fluid). The sources property specifies the source video for the player, in this case, an MP4 file.

const videoJsOptions = {
    autoplay: false,
    controls: true,
    responsive: true,
    fluid: true,
    sources: [{
      src: 'https://media-files.vidstack.io/720p.mp4',
      type: 'video/mp4'
    }]
  };Code language: JavaScript (javascript)

Also, define a handlePlayerReady function passed to the VideoJS component through the onReady prop. This function receives the video.js player instance as an argument and stores it in the refPlayer ref. It also sets up event listeners for the waiting and dispose events, which log messages to the console when they are triggered.

const handlePlayerReady = (player) => {
    refPlayer.current = player;

    // You can handle player events here, for example:
    player.on('waiting', () => {
      videojs.log('player is waiting');
    });

    player.on('dispose', () => {
      videojs.log('player will dispose');
    });
  };

return (
    <>
      <div>Rest of app here</div>
      <VideoJS options={videoJsOptions} onReady={handlePlayerReady} />
      <div>Rest of app here</div>
    </>
  );Code language: JavaScript (javascript)

The App component renders the VideoJS component and includes it in the JSX returned by the component, along with some additional content before and after the player. When the component is rendered, the VideoJS component will create a video.js player using the provided options and pass it to the handlePlayerReady function through the onReady prop, allowing the App component to interact with the player through the refPlayer ref.

For more information, check out the official documentation at: React and Video.js | Video.js (videojs.com)

You can check out the code here: video.js (codedamn.com)

React-player

React Player is a lightweight, customizable, and extendable media player for the web that is built using the popular JavaScript library, React. It is designed to be easy to use and integrate into any React-based application.

One of the main benefits of using React Player is that it allows developers to create custom media players without dealing with the complexities of HTML5 video and audio APIs. It means that developers can focus on creating the desired user experience and custom functionality rather than spending time on low-level implementation details.

React Player is highly customizable and can easily be extended to support new media types or additional functionality. It has several built-in features, such as support for multiple file formats, playback controls, and a responsive design that adjusts to different screen sizes and devices.

React Player is a powerful tool for building custom media players for the web and is particularly well-suited for React-based applications. It allows developers to quickly and easily create a media player that meets their specific needs and requirements without dealing with the underlying complexities of HTML5 video and audio APIs.

You will first need to install the library using npm or yarn to use React Player in a React-based application. You can do this by running the following command in your terminal:

npm install react-playerCode language: JavaScript (javascript)

or

yarn add react-playerCode language: JavaScript (javascript)

Once the library is installed, you can import it into your application and use it to render a media player. Here’s an example of how you might use React Player to render a simple video player:

import React from 'react';
import ReactPlayer from 'react-player';

function VideoPlayer() {
  return (
    <ReactPlayer
      url="<https://www.youtube.com/watch?v=ysz5S6PUM-U>"
      width="640"
      height="360"
      controls
    />
  );
}

export default VideoPlayer;Code language: JavaScript (javascript)

This will render a video player with the specified URL, dimensions, and controls. You can customize the player by passing additional props to the component. For example, you can use the playing prop to specify whether the player should start playing automatically or the volume prop to set the initial volume level.

In addition to the built-in props, React Player also supports custom props that you can use to extend the player’s functionality. For example, you can use the onReady prop to specify a callback function that will be called when the player is ready to play or the onEnded prop to set a callback function that will be called when the player finishes playing.

To reduce your bundle size, you can import a specific player, such as the YouTube player, using import ReactPlayer from ‘react-player/youtube’. This will allow you to play YouTube videos using the ReactPlayer component, like so:

import React from 'react';
import ReactPlayer from 'react-player/youtube';

function MyComponent() {
  return (
    <div>
      <ReactPlayer url='https://www.youtube.com/watch?v=ysz5S6PUM-U' />
    </div>
  );
}

export default MyComponent;Code language: JavaScript (javascript)

The react-player package also offers other player components for specific media types, such as react-player/vimeo for Vimeo videos and react-player/soundcloud for SoundCloud audio. You can find the complete list of player components in the react-player documentation.

If your build system supports the import() statement, you can use the react-player/lazy package to lazy load the appropriate player for the media file you want to play. This can help reduce the size of your main bundle by only loading the necessary player when needed.

To use the react-player/lazy package, you can import it into your React component like this:

import React from 'react';
import ReactPlayer from 'react-player/lazy';

function MyComponent() {
  return (
    <div>
      <ReactPlayer url='https://www.youtube.com/watch?v=ysz5S6PUM-U' />
    </div>
  );
}

export default MyComponent;Code language: JavaScript (javascript)

This will help lazy load the YouTube player when the ReactPlayer component is rendered. You can use the react-player/lazy package to play other media types by passing in the appropriate URL. Remember that using the react-player/lazy package will add several player chunks to your output.

For more information on how to use the react-player/lazy package, you can refer to the react-player documentation.

Overall, React Player is a powerful and flexible tool for building custom media players in React-based applications. Whether you need a simple player with basic controls or a more advanced player with custom functionality, React Player has you covered.

You can check out the code here: react-player (codedamn.com)

Video-React

Video-React is a popular JavaScript library for building user interfaces with video playback functionality. It is built on the React JavaScript library, a widely-used framework for building user interfaces.

Video-React provides a simple and flexible API for integrating video playback into a web application. It offers a range of features such as:

  • Support for HTML5 video and YouTube videos
  • Responsive design that automatically adjusts to the size of the container element
  • Customizable controls such as play/pause, volume, and fullscreen
  • Support for captions and subtitles
  • The ability to play multiple videos in a playlist

To use Video-React, install the Video-React package using a package manager such as npm or yarn.

Install video-react

npm install video-react Code language: JavaScript (javascript)

import CSS in your app or add video-react styles in your page

import '~video-react/dist/video-react.css'; // import cssCode language: JavaScript (javascript)

Once you have installed Video-React, you can add video playback to your application using the Player component. This component allows you to specify the source of the video and any other desired options, such as the controls, autoplay, and loop.

Here is an example of how you might use the Video-React library to add a video to your application:

import React from 'react';
import { Player, ControlBar } from 'video-react';
import 'video-react/dist/video-react.css';

export function MyVideoPlayer()  {
  return (
    <Player autoPlay src="https://media.w3.org/2010/05/sintel/trailer_hd.mp4">
      <ControlBar autoHide={false} className="my-class" />
    </Player>
  );
};Code language: JavaScript (javascript)

This code will create a video player with controls and autoplay enabled to play the video at “https://media.w3.org/2010/05/sintel/trailer_hd.mp4“.

Overall, Video-React is a powerful and easy-to-use library that can significantly simplify the process of adding video playback to a React application.

You can check out the code here: video-react (codedamn.com)

React-youtube

React-youtube is a simple React component that allows you to embed a YouTube video player on your website. It acts as a thin layer over the YouTube IFrame Player API and provides various options for customizing the player and binding events to playback.

To use react-youtube, you can install it using npm or yarn by running the following command:

npm install react-youtubeCode language: JavaScript (javascript)
yarn add react-youtubeCode language: JavaScript (javascript)

Once installed, you can use the YouTube component in your React code by importing it like this:

import YouTube from 'react-youtube';Code language: JavaScript (javascript)

The YouTube component takes several props, allowing you to customize the video player and bind events to it. Some of the props include:

  • videoId: a string that specifies the YouTube video ID to be played.
  • id: a string that specifies the ID of the YouTube element.
  • className: a string that specifies the class name of the YouTube element.
  • iframeClassName: a string that specifies the class name of the iframe element that embeds the video player.
  • style: an object that specifies the inline styles of the YouTube element.
  • title: a string that specifies the title of the video.
  • loading: a string that specifies the loading message to be displayed while the video player is loading.
  • opts: an object that specifies player options such as the width and height of the player and player parameters.
  • onReady: a function that is called when the video player is ready.
  • onPlay: a function that is called when the video starts playing.
  • onPause: a function that is called when the video is paused.
  • onEnd: a function that is called when the video ends.
  • onError: a function called when an error occurs while playing the video.
  • onStateChange: a function called when the state of the video player changes.
  • onPlaybackRateChange: a function that is called when the playback rate of the video changes.
  • onPlaybackQualityChange: a function that is called when the playback quality of the video changes.

Here is an example of how to use the YouTube component in a React component:

import React, { useRef } from 'react';
import YouTube from 'react-youtube';

const Example = () => {

  const opts = {
    height: '390',
    width: '640',
    playerVars: {
      autoplay: 1,
    },
  };

  const onReady = (event) => {
    // access to player in all event handlers via event.target
    event.target.pauseVideo();
  };

  return (
    <YouTube
      videoId="2g811Eo7K8U"
      opts={opts}
      onReady={onReady}
    />
  );
};

export default Example;Code language: JavaScript (javascript)

In the above example, we are rendering a YouTube component with a video ID of “2g811Eo7K8U”. We are also specifying player options, such as the height and width of the player, and setting the autoplay player parameter to 1, which will cause the video to start playing automatically when the player is loaded.

We also bind an event handler function to the onReady prop, which will be called when the video player is ready. In the event handler function, we access the player via the event.target property and call the pauseVideo method to pause the video.

Finally, you can control the player by accessing it via the event.target property in the event handler functions and calling methods such as playVideopauseVideostopVideo, and seekTo on it.

You can check out the code here:react-youtube (codedamn.com)

Conclusion

In conclusion, many great options exist for rendering videos in React applications. Whether you need a powerful and feature-rich library like Vidstack.io or a simple and lightweight solution like ReactPlayer, there is a React video player library that can meet your needs and requirements.

Sharing is caring

Did you like what Husain Mohammed Bhagat wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far