<main></main>

// 3. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.

const youtubeReady = new Promise(function(resolve, reject) {
  window.onYouTubeIframeAPIReady = function() {
    resolve(YT.Player);
  };
});

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { playing: false };
  }
  
  toggle() {
    this.setState({ playing: !this.state.playing });
  }
  
  componentDidUpdate(prevProps, prevState) {
    if (this.state.playing) {
      this.player.playVideo();
    } else {
      this.player.pauseVideo();      
    }
  }
  
  componentDidMount() {
    youtubeReady.then((Player) => {
      this.player = new Player(this.el, {
          height: '390',
          width: '640',
          videoId: 'M7lc1UVf-VE',        
      });
    });
  }
  
  render() {
    return (
      <div>
        <p>
          <button onClick={() => this.toggle()}>Play / Pause</button>
          Current state: {this.state.playing ? 'Play' : 'Stop'}
        </p>
        
        <div ref={(el) => {this.el = el; }}></div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.querySelector('main'));
View Compiled
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/react/16.3.1/umd/react.development.js
  2. https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.3.1/umd/react-dom.development.js
  3. https://www.youtube.com/iframe_api