I tried to load youtube videos under 3 tabs in a page. In the initial load of the react component, the video under first page works well. If navigated to the second or third tab, the youtube player is not mounting in the DOM. What i understood from this behavior during the tab switch is, the 'onYouTubeIframeAPIReady' event is not triggering from the downloaded script after switching the tabs. I ensured that on each tab switch the component is rendered and new script is downloaded from the iFrame api.
import {
Component
} from 'react';
class VideoPlayer extends Component {
componentDidMount() {
const id = 'youtube-id';
if (!document.getElementById(id)) {
const tag = document.createElement('script');
tag.setAttribute('src', 'https://www.youtube.com/iframe_api');
tag.setAttribute('id', id);
document.body.appendChild(tag);
window.youtubeFrames = [];
window.onYouTubeIframeAPIReady = this.loadYoutubeVideo;
}
window.youtubeFrames.push({
video: this.video,
videoId: this.props.Id,
});
}
componentWillUnmount() {
const elem = document.getElementById('youtube-id');
if (elem) {
elem.parentNode.removeChild(elem);
}
}
loadYoutubeVideo = () => {
let player;
window.youtubeFrames.forEach((youtubeFrame) => {
if (youtubeFrame.video) {
player = new YT.Player(youtubeFrame.video, {
height: `${this.video.style.height}px`,
width: '100%',
videoId: youtubeFrame.videoId,
playerVars: {
rel: 0,
},
events: {
onStateChange: (e) => {
if (e.data === 0) {
youtubeFrame.coverFrame.classList.remove('play');
} else {
youtubeFrame.coverFrame.classList.add('play');
}
},
},
});
}
});
/* eslint-enable */
}
render() {
const videoRef = arg => (this.video = arg);
return ( <
div className = "youtube-video"
ref = {
coverRef
} >
<
div className = "video"
ref = {
videoRef
}
/> < /
div >
);
};
}
export default VideoPlayer;