Skip to content

Instantly share code, notes, and snippets.

@pdewouters
Last active December 19, 2019 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pdewouters/d19b196084d8d7cdc01726f328db0e7c to your computer and use it in GitHub Desktop.
Save pdewouters/d19b196084d8d7cdc01726f328db0e7c to your computer and use it in GitHub Desktop.
youtube
import React, { useRef, useEffect } from 'react';
import PropTypes from 'prop-types';
import { Waypoint } from 'react-waypoint';
function Youtube( { youtubeId } ) {
const playerRef = useRef( null );
const elementRef = useRef( null );
const loadVideo = () => {
const player = new window.YT.Player( elementRef.current, {
host: 'https://www.youtube.com',
height: '100%',
width: '100%',
videoId: youtubeId,
events: {
'onReady': () => playerRef.current = player,
},
playerVars: {
'origin': window.location.origin,
'enablejsapi': 1,
},
} );
};
const loadAPI = () => {
const youtubeScriptId = 'youtube-api';
const youtubeScript = document.getElementById( youtubeScriptId );
if ( youtubeScript === null ) {
const tag = document.createElement( 'script' );
const firstScript = document.getElementsByTagName( 'script' )[0];
tag.src = 'https://www.youtube.com/iframe_api';
tag.id = youtubeScriptId;
firstScript.parentNode.insertBefore( tag, firstScript );
}
window.onYouTubeIframeAPIReady = () => document.dispatchEvent( new Event( 'youtube-loaded' ) );
};
useEffect( () => {
if ( window.YT && window.YT.loaded ) {
loadVideo();
} else {
document.addEventListener( 'youtube-loaded', loadVideo );
loadAPI();
}
return () => {
document.removeEventListener( 'youtube-loaded', loadVideo );
}
}, [] );
const handleLeave = () => {
playerRef.current && playerRef.current.pauseVideo();
};
return (
<Waypoint
onLeave={ handleLeave }
topOffset='100px'
scrollableAncestor={ window }
>
<div className="youtube-container">
<div ref={ elementRef }></div>
</div>
</Waypoint>
);
}
Youtube.propTypes = {
youtubeId: PropTypes.string.isRequired,
};
export default Youtube;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment