Create a Video player with react-player which supports mp4, Youtube and Vimeo videos with ReactJS

Here’s an example of a video player in React that supports MP4, YouTube, and Vimeo videos.

We’ll be using the react-player library to handle playing the videos, and we’ll render different components based on the type of video we’re playing.

First, let’s install the library:

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

Next, let’s create our video player component:

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

const VideoPlayer = ({ url }) => {
  const isYoutube = url.includes('youtube.com');
  const isVimeo = url.includes('vimeo.com');

  if (isYoutube) {
    const videoId = url.split('v=')[1];
    return (
      <ReactPlayer
        url={`https://www.youtube.com/watch?v=${videoId}`}
        width="100%"
        height="100%"
      />
    );
  }

  if (isVimeo) {
    const videoId = url.split('vimeo.com/')[1];
    return (
      <ReactPlayer
        url={`https://vimeo.com/${videoId}`}
        width="100%"
        height="100%"
      />
    );
  }

  return (
    <ReactPlayer
      url={url}
      controls
      width="100%"
      height="100%"
    />
  );
};

export default VideoPlayer;

Here’s how the component works:

  • We start by checking if the URL contains “youtube.com” or “vimeo.com” to determine the type of video we’re playing.
  • If it’s a YouTube video, we extract the video ID from the URL and pass it to the ReactPlayer component with the correct URL format.
  • If it’s a Vimeo video, we do the same thing but with the Vimeo URL format.
  • If it’s neither a YouTube nor Vimeo video, we just render the ReactPlayer component with the URL.
  • We also add the controls prop to show the video controls and set the width and height props to 100% to make the video player fill its container.

Now let’s use the component in our app:

import React from 'react';
import VideoPlayer from './VideoPlayer';
const App = () => {
  return (
    <div>
      <VideoPlayer url="https://www.youtube.com/watch?v=dQw4w9WgXcQ" />
      <VideoPlayer url="https://vimeo.com/522772021" />
      <VideoPlayer url="https://example.com/example.mp4" />
    </div>
  );
};
export default App;

In this example, we’re rendering three videos with different URLs: a YouTube video, a Vimeo video, and an MP4 video. The VideoPlayer component will handle playing all of them.

And here’s a demo of the video player in action: https://codesandbox.io/s/reactplayerdemo-mokjcd

Leave a Reply

Your email address will not be published. Required fields are marked *