Welcome folks today in this blog post we will be embeding youtube video
in iframe
tag using react.js. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new react.js
project using the below command as shown below
npx create-react-app sampleapp
cd sampleapp
And now you need to edit the App.js
file of your react.js app and copy paste the below code
App.js
1 2 3 4 5 6 7 8 9 10 11 12 |
import React from "react"; import "./styles.css"; import YoutubeEmbed from "./YoutubeEmbed"; export default function App() { return ( <div className="App"> <h1>React Youtube Embedding Example</h1> <YoutubeEmbed embedId="rokGy0huYEA" /> </div> ); } |
As you can see in the above javascript
code we are including the youtubeEmbed
component where we are passing the embedId
to this component so that we can display the youtube video
in iframe tag.
Now we need to create the YoutubeEmbed.js
file and copy paste the following code
YoutubeEmbed.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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; |
As you can see inside this we have the iframe
tag in which we are providing the width
and the height
attributes and then we have the src
of the video where we are attaching the embedId
of the video the url
. And then we are attaching the frameborder
and also we are adding the allowfullscreen
attribute as well.
Now if you open the application
inside the browser you will see the below result