This React hook lets you use the YouTube IFrame Player API easily. It gives you the player, and you can start using the official YouTube Player API for IFrame reference in your project.
For the Vanilla JS version you can check out youtube-iframe-api-module.
npm install react-youtube-iframe-playerimport { useYoutubeIframeApi } from "react-youtube-iframe-player";
import { useMemo } from 'react';
function App() {
const { player, isPlayerReady } = useYoutubeIframeApi('player', useMemo(() => ({
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
playerVars: {
playsinline: 1
},
events: {
onReady: (event) => {
const player = event.target;
const videoData = player.getVideoData();
console.log('title', videoData.title)
}
}
}), []));
return (
<div>
<div id="player"></div>
</div>
);
}The useYoutubeIframeApi() hook takes two parameters just like the YouTube Player API: tag id and options.
const { player, isPlayerReady } = useYoutubeIframeApi(tagId, options)-
Consider using the
useMemo()otherwise the hook will not work. -
playerwill beundefinedin the first place since the YouTube IFrame API is added dynamically and consider not to use during render. Call its methods through event methods like:const onStopClick = () => { player.stopVideo() }
-
Since
playerisundefinedin the first place consideroptional chainingcheck before using it. You can applyisPlayerReadytoo. When theplayerinstance ready it will betrue -
You can access the
playerinstance withevent.targetin the event definitions.