Adding YouTube Video in React

Tiempo de lectura: < 1 minuto

Today we’re going to learn how we can add a YouTube video in React.

The first thing we need to do is to add this dependency:

npm install react-youtube --save

Once installed, let’s create the component responsible for opening the YouTube video.

We’ll call it YoutubePlayer.tsx

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

interface Props {
  idYoutubeVideo: string;
}

const YoutubePlayer: React.FC<Props> = ({ idYoutubeVideo }) => {

  const opts: YouTubeProps['opts'] = {
    height: '390',
    width: '640',
  };

  const onPlayerReady: YouTubeProps['onReady'] = (event) => {
    // access to player in all event handlers via event.target
    event.target.pauseVideo();
  }

  return (
    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
      <YouTube videoId={idYoutubeVideo} opts={opts} onReady={onPlayerReady} id="video" />
    </div>
  );
};

export default YoutubePlayer;

You can customize the options by adding playerVars: reference.

  const opts: YouTubeProps['opts'] = {
    height: '390',
    width: '640',
    playerVars: {
      // https://developers.google.com/youtube/player_parameters
      //autoplay: 1,
    },
  };

And this is the result:

Leave a Comment