I installed youtube-react API and you I got the onPlay function to work but the issue was it was very slow to load videos <YouTube videoId={Projects.videoID} onPlay={autoplayChange} onPause={autoplayChange} onEnd={autoplayChange}/>
How can I recreate this similar function using a regular iframe with the youtube API? I can't find any documentation about implementing this into reactjs. https://developers.google.com/youtube/iframe_api_reference googles API reference mentions the functions under onStateChange but I cant figure out the implementation I thought someone on here might have an answer to my problem. Thanks in advance.
Check out react-player
, you can install it quickly with npm:
npm install react-player
It is fast and will give you a lot of control over the onPlay functionality that you are looking for. Example from the git:
import React from 'react'
import ReactPlayer from 'react-player/lazy'
// Lazy load the YouTube player
<ReactPlayer url='https://www.youtube.com/watch?v=ysz5S6PUM-U' />
With hooks you can add onPlay functionality like so:
import React, { useState } from 'react'
import ReactPlayer from 'react-player/lazy'
const MyPlayer = () => {
const [ playState, setPlayState ] = useState(false);
const yourFunction = (event) => {
console.log('Your event: ', event);
};
return (
<ReactPlayer
url='https://www.youtube.com/watch?v=ysz5S6PUM-U'
playing={playState}
onPlay={yourFunction}/>
);
}