Embed YouTube Video on React Application

While working on my last project, I wanted to add links to youtube videos. At first, I added an image with a targeted link to youtube, but after re-thinking about the user experience, realized that I want to embed the video for a smoother experience.

A quick search provided me a few different packages, such as react-youtube or React-player, but I love to create on my own and try to write a simple responsive component with embedded YouTube videos. I was surprised at how easy it was. Here is how I did it.

I started by exploring the iframe tag, an HTML element that allows an external website to display on another website. Iframe tag, short for an inline frame, must have source attribute, a link to the website to render. Other typical attributes will be a title, style, and framBorder. Youtube made it so simple: copy the embed link from Youtube, and you halfway to achieving your goal.

copy embed code from YouTube
copy embed code from YouTube
<iframe width=”793" height=”580" src=”https://www.youtube.com/embed/RfApZrbvUic" frameborder=”0" allow=”accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture” allowfullscreen></iframe>

There are already pre-set values for width and height; those values prevent the Iframe from being responsive. To make it responsive, we need to make few adjustments to the style attribute (or adding to the CSS file).

Here is my final code:

Note: I wrapped the Iframe tag in a div and added padding-bottom attribute set to 56.25% in order to keep the ratio for the screen.

Good Luck!