Caleb

Build a re-usable YouTube embed component with React

August 20, 2022 3 min read

One of the perks that comes with React is the total adoption of the DRY — Don't Repeat Yourself — paradigm in Software Engineering. You can decide to create utility components that can be used throughout the codebase, when you begin to notice that you're doing a particular thing over and over again.

In this article, we'll go over how you can create a re-usable YouTube embed component with React. Sometimes, having to copy the embed code from YouTube and paste it int your project can cause a lot of clutter in the codebase, which in turnmay reduce the readability of such code.

The ideal process would be to create the component file, copy and paste the YouTube embed markup in the component, then export the component so it is available throughout the project.

Take a look at the structure of the markup below.

<iframe
  width="560"
  height="315"
  src="https://www.youtube.com/embed/a-random-string"
  title="YouTube video player"
  frameborder="0"
  allow="
    accelerometer; 
    autoplay; 
    clipboard-write; 
    encrypted-media; 
    gyroscope; 
    picture-in-picture"
  allowfullscreen
></iframe>

The next step in the process is to create a component that we can wrap the iframe element in, and allow the component to receive the video id as a prop.

export default function EmbedYouTube({ video }) {
  return (
    <iframe
      width="560"
      height="315"
      src={`https://www.youtube.com/embed/${video}`}
      title="YouTube video player"
      frameBorder="0"
      allow="
        accelerometer; 
        autoplay; 
        clipboard-write; 
        encrypted-media; 
        gyroscope; 
        picture-in-picture"
      allowFullScreen
    ></iframe>
  )
}

In the snippet above, you'll notice that we passed video prop as a variable in the string-literal that represents the id of the video. It — the video prop — becomes what you'll use to assign the id of any video link you copied from YouTube when yo begin to reuse the component across your project or codebase.

All you'd need to do when you want to use the component is to import it from the directory that it is situated.

import EmbedYouTube from "./components/EmbedYoutube";

<EmbedYouTube video={"ykV21873wwhga"}

The string is appended aft of the YouTube link. Something similar to what is shown below

'https://www.youtube.com/embed/ykV21873wwhga'

You can go ahead to customize the component as you wish with CSS, and implement how you want the layout of the component to be, in various viewport with CSS media queries.

Thank you for reading through, I hope it has been helpful to you.