index.js

import React, { useState } from 'react';
import { useLocation } from 'react-router';
import YouTube from 'react-youtube';
import { sendEventViewItem } from '../../../utility/analytics/events';
import { PlayerState, PlayerStateText } from '../../../utility/constants/youtube-player';

import './index.scss';

export default function YoutubePlayer({ id }) {
  const [playerState, setPlayerState] = useState(null);
  const location = useLocation();
  const opts = {
    playerVars: {
      // https://developers.google.com/youtube/player_parameters
      autoplay: 1
    }
  };

  // Analytics
  function send() {
    sendEventViewItem({ videoId: id }, location);
  }

  function onVideoPlay() {
    const playerStateText = PlayerStateText(PlayerState.PLAYING);
    setPlayerState(playerStateText);
  }

  function onVideoEnd() {
    const playerStateText = PlayerStateText(PlayerState.ENDED);
    setPlayerState(playerStateText);
  }

  return (
    <div className={`youtube-player-wrapper ${playerState}`} onClick={send}>
      <YouTube videoId={id} opts={opts} onPlay={onVideoPlay} onEnd={onVideoEnd} />
    </div>
  );
}