DEV Community

Cover image for Simplest way to embed a Youtube video in your React app
bravemaster619
bravemaster619

Posted on

Simplest way to embed a Youtube video in your React app

Overview

  • Quick and simple
  • No npm i
  • Fully responsive
  • Feel free to Copy & Paste

1. Make a component for iframe:

YoutubeEmbed.js

import React from "react";
import PropTypes from "prop-types";

const YoutubeEmbed = ({ embedId }) => (
  <div className="video-responsive">
    <iframe
      width="853"
      height="480"
      src={`https://www.youtube.com/embed/${embedId}`}
      frameBorder="0"
      allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
      allowFullScreen
      title="Embedded youtube"
    />
  </div>
);

YoutubeEmbed.propTypes = {
  embedId: PropTypes.string.isRequired
};

export default YoutubeEmbed;
Enter fullscreen mode Exit fullscreen mode

2. Add some css for responsiveness:

styles.css

.video-responsive {
  overflow: hidden;
  padding-bottom: 56.25%;
  position: relative;
  height: 0;
}

.video-responsive iframe {
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
  position: absolute;
}

Enter fullscreen mode Exit fullscreen mode

3. Use it

Couldn't be simpler. Easy-breezy:

import React from "react";
import "./styles.css";
import YoutubeEmbed from "./YoutubeEmbed";

export default function App() {
  return (
    <div className="App">
      <h1>Youtube Embed</h1>
      <YoutubeEmbed embedId="rokGy0huYEA" />
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Result

Latest comments (19)

Collapse
 
athul_jose_bb907dcdcb66e8 profile image
Athul Jose

can we hide the info of the video and the links that redirect to youtube

Collapse
 
boyld222 profile image
Tri Kiet

Really really need it, thank you very much !

Collapse
 
jacobdchamberlain profile image
Jacob D. Chamberlain

This was super helpful, and straight to the point. Thank you so much!

Collapse
 
danielngan17 profile image
Daniel Ngan

can you write it in functional components?

Collapse
 
jjrh92 profile image
Julio

Thank you.

Collapse
 
juansystems profile image
JuanSystems

Funciona bien. Pero me sale este error 404 en la consola de chrome:

GET youtube.com/img/meh7.png 404 index.js:1962

Image description

Collapse
 
hhsm95 profile image
Hugo Sandoval

Thanks, works like a charm!

Collapse
 
britt_joiner profile image
Brittany Joiner

This was awesome! Worked really well for me as well!

Collapse
 
tomshaw profile image
Tom Shaw

Nice!

Collapse
 
nivethan profile image
Nivethan Ariyaratnam • Edited

the example video shows a thumbnail as expected but when i try with 2 videos they don't show any thumbnail but just a black screen! do you have any idea?