youtube
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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