Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to integrate Youtube Iframe api in reactjs solution

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 ?

like image 875
habibalsaki Avatar asked Jan 03 '19 06:01

habibalsaki


People also ask

Can we use iframe in Reactjs?

In React, developers use iframes to create either a sandboxed component or an application that is isolated from its parent component. In an iframe, when a piece of content is embedded from an external source, it is completely controlled by the source instead of the website it is embedded in.

How do I open iframe in react JS?

import React from "react"; import ReactDOM from "react-dom"; function App() { return ( <div className="App"> <h1>Iframe Demo</h1> <Iframe iframe={iframe} />, </div> ); } const rootElement = document. getElementById("root"); ReactDOM. render(<App />, rootElement);


1 Answers

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>
like image 178
Bill Avatar answered Sep 24 '22 05:09

Bill