11. Make a component for iframe:
2
3//YoutubeEmbed.js
4import React from "react";
5import PropTypes from "prop-types";
6
7const YoutubeEmbed = ({ embedId }) => (
8 <div className="video-responsive">
9 <iframe
10 width="853"
11 height="480"
12 src={`https://www.youtube.com/embed/${embedId}`}
13 frameBorder="0"
14 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
15 allowFullScreen
16 title="Embedded youtube"
17 />
18 </div>
19);
20
21YoutubeEmbed.propTypes = {
22 embedId: PropTypes.string.isRequired
23};
24
25export default YoutubeEmbed;
262. Add some css for responsiveness:
27styles.css
28.video-responsive {
29 overflow: hidden;
30 padding-bottom: 56.25%;
31 position: relative;
32 height: 0;
33}
34
35.video-responsive iframe {
36 left: 0;
37 top: 0;
38 height: 100%;
39 width: 100%;
40 position: absolute;
41}
42
433. Use it
44Couldn't be simpler. Easy-breezy:
45import React from "react";
46import "./styles.css";
47import YoutubeEmbed from "./YoutubeEmbed";
48
49export default function App() {
50 return (
51 <div className="App">
52 <h1>Youtube Embed</h1>
53 <YoutubeEmbed embedId="rokGy0huYEA" />
54 </div>
55 );
56}