Autoplay YouTube Embed in React
Sometime you might need to embed youtube video to your react application and you want it to autoplay.
You can do that by using this tricks:
Add this query param to the URL to embed.
?playsinline=1
: This parameter tells the video to play inline (within the embedded frame) rather than in full-screen mode.&iv_load_policy=3
: This parameter controls whether video annotations (info cards) are enabled. "3" specifies that annotations are turned off.&rel=0
: This parameter disables related videos from appearing at the end of the video playback.&showinfo=0
: This parameter hides video information such as the video title and uploader's information.&controls=1
: This parameter enables video player controls, including the play/pause button, volume control, and progress bar.&fs=0
: This parameter disables the option for viewers to enter full-screen mode.&start=10
: This parameter specifies the time at which the video will start playing. In this case, the video will start at 10 seconds into the video.&autoplay=1
: This parameter automatically starts playing the video when the page loads. "1" indicates that autoplay is enabled.&enablejsapi=1
: This parameter allows the use of the YouTube JavaScript API, which enables programmatic control of the video player and interaction with the video.&widgetid=1
: This parameter specifies a unique widget identifier, which can be useful when working with the YouTube JavaScript API.
export function YoutubePlayer({
videoId,
start,
}: {
videoId: string;
start: number;
}) {
return (
<div className="youtube-frame">
<iframe
width="640"
height="360"
src={`https://www.youtube.com/embed/${videoId}?playsinline=1&iv_load_policy=3&rel=0&showinfo=0&controls=1&fs=0&start=${start}&autoplay=1&enablejsapi=1&widgetid=1`}
title="YouTube video player"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowFullScreen
></iframe>
</div>
);
}
Bonus
Let's add css to make it responsive.
.youtube-frame {
overflow: hidden;
padding-bottom: 56.25%;
position: relative;
height: 0;
}
.youtube-frame iframe {
left: 0;
top: 0;
height: 100%;
width: 100%;
position: absolute;
}