So this came up on a recent project I was working on, I wanted to embed some videos onto a site, and the videos were already posted on YouTube. I knew from previous experience it’s possible to embed files directly onto a webpage, but I wasn’t sure how to go about this. After a little research, I read up on the tag <iframe>. Here, I’ll give a quick breakdown of how they worked within my code, as well as some of the troubleshooting I went through implementing it into my code.

For starters, this particular video was going to be held within its own React component, so implementation was pretty straightforward. For the purposes of this article, we’ll use the YouTube video linked here (this video is actually my demo for my final Flatiron Project that I called “What’s For Dinner”). One of the most important pieces to consider when implementing a YouTube-hosted video in your code is to know the video’s ID tag. If you look at the link specifically for the video, you’ll see the link displayed as: “https://www.youtube.com/watch?v=upTcsAW4w1k”. This last piece, following the “v=” is the tag for the video, which we will come back to later.

Using the iframe HTML tag requires only two attributes. The first is the source video, using the src attribute. The second is the title, which was necessary to include as my code returned an error without it on compiling. In the case of my code, I wanted to include some minor in-HTML styling, to make sure the video would be consistently shown across different users. The basic component came out like so:

Functional Component for Demo1

As you can see, the iframe tag took both width and heigh, as well as the source and title for the video. One specific thing I would like to point to is the difference in the link from the video I linked above. Because this is being embedded into code, as opposed to being watched on YouTube’s site, the src for this video had to include the “/embed” within the link, followed by the ID tag I had referenced earlier. If you attempted to use the link mentioned earlier, an error is shown where you intended the video box to be.

Further, on the styling, you can see that the iframe can take a width and height, which will change the size of the embedded YouTube video within your code. As needed, many other attributes can be used depending on the styling needs of your code.

Short aside: I have found myself using the <center> tag more often when I build my components, and I’ve found it to be an elegant alternative to manually changing CSS files, which many can find frustrating.

Once the code run, we had a page that looked like below, with all controls fully functional as if the video were being played through YouTube’s site directly.

And that’s iframe tags in a nutshell! Enjoy embedding videos into your code going forward!

Flatiron School DC. Learning to code one day at a time.