12

In react, I am trying to create a component for custom youtube player, so that I can introduce a new player controls bar. Form youtube iframe API, it was mentioned to use following code to create a player instance,

var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

But when I am trying to use this code on react component life-cycle methods (like componentDidUpdate) YT instance isn't found at all.

Any solution to this ?

habibalsaki
  • 1,082
  • 4
  • 13
  • 25

2 Answers2

36

Here is a YouTubeVideo React component I wrote for a project recently.

When the component mounts, it checks to see if the YouTube iFrame API has already been loaded.

  • If so, then it calls the API to create a new YouTube Player object directly.
  • If not, it first waits for the script to load asynchronously and then load the video.

import PropTypes from 'prop-types';
import React from 'react';

import classes from 'styles/YouTubeVideo.module.css';

class YouTubeVideo extends React.PureComponent {
  static propTypes = {
    id: PropTypes.string.isRequired,
  };

  componentDidMount = () => {
    // On mount, check to see if the API script is already loaded

    if (!window.YT) { // If not, load the script asynchronously
      const tag = document.createElement('script');
      tag.src = 'https://www.youtube.com/iframe_api';

      // onYouTubeIframeAPIReady will load the video after the script is loaded
      window.onYouTubeIframeAPIReady = this.loadVideo;

      const firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    } else { // If script is already there, load the video directly
      this.loadVideo();
    }
  };

  loadVideo = () => {
    const { id } = this.props;

    // the Player object is created uniquely based on the id in props
    this.player = new window.YT.Player(`youtube-player-${id}`, {
      videoId: id,
      events: {
        onReady: this.onPlayerReady,
      },
    });
  };

  onPlayerReady = event => {
    event.target.playVideo();
  };

  render = () => {
    const { id } = this.props;
    return (
      <div className={classes.container}>
        <div id={`youtube-player-${id}`} className={classes.video} />
      </div>
    );
  };
}

export default YouTubeVideo;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Bill
  • 764
  • 6
  • 14
0

Alternatively to the solution above you could use react-youtube.

Installtion:

npm install react-youtube

Usage:

import React from "react";
import YouTube from "react-youtube";

function App() {
  const onPlayerReady = (event) => {
    const player = event.target;
    player.pauseVideo();
  };

  const onPlayerStateChange = (event) => {
    const player = event.target;
    player.playVideo();
  };

  const options = {
    height: "390",
    width: "640",
    playerVars: {
      autoplay: 1,
    },
  };

  return (
    <YouTube
      videoId="AaGK-fj-BAM"
      opts={options}
      onReady={onPlayerReady}
      onStateChange={onPlayerStateChange}
    />
  );
}

export default App;

The library also supports TypeScript, check out the second example in the Readme if that's what you're interested in.

gignu
  • 1,763
  • 1
  • 14
  • 24