I am using the Youtube Iframe API’s first example in my react app. The problem I am facing is that when I reload the page everything works fine for the first time but when I change any settings like autoplay, loop from sidebar it stops working. I am following the first Iframe example from the documentation.
I am expecting that If i change any settings from sidebar, everything should works just fine.
Heres what I have tried —
import "./styles.css";
import { useEffect } from "react";
export default function App({config}) {
useEffect(() => {
const tag = document.createElement("script");
tag.id = "iframe-demo";
tag.src = "https://www.youtube.com/iframe_api";
const firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
let player;
window.onYouTubeIframeAPIReady = () => {
player = new window.YT.Player("existing-iframe-example", {
events: {
onReady: (e) => {
console.log("on player ready", e);
player.mute();
},
onStateChange: (e) => {
if (e.data === window.YT.PlayerState.ENDED && true) {
console.log("video ended", player);
player.seekTo(5 || 0);
}
},
},
});
};
}, [config?.autoplay, config?.isVideoMute]);
return (
<div className="App">
<iframe
id="existing-iframe-example"
width="640"
height="360"
src={`https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&start=5&end=8&mute=${config?.isVideoMute}&autoplay=${config?.isAutoPlay}`}
frameborder="0"
></iframe>
</div>
);
}
Take a look at the Iframe src attribute. From my settings panel, I am controlling the mute and autoplay config. So, when I change any value of these settings, the Youtube Player API onStateChange does not fire.