Welcome folks today in this blog post we will be embeding youtube video
in iframe
using react-youtube
and get-youtube-id
library in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the below libraries
using the below command as shown below
npm i react-youtube
npm i get-youtube-id
After that you need to make the App.js
file inside the react.js project and copy paste the below code
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import React, { useState } from "react"; import YouTube from "react-youtube"; var getYouTubeID = require("get-youtube-id"); export default function App() { const [id, setId] = useState("ZjJYqDjmGkI"); function handleChange(e) { console.log(e.target.value); setId(getYouTubeID(e.target.value)); } const opts = { height: "390", width: "640", playerVars: { // https://developers.google.com/youtube/player_parameters autoplay: 1 } }; return ( <div className="App"> <input type="text" onChange={handleChange} required placeholder="URL..." /> <YouTube videoId={id} opts={opts} onReady={this._onReady} /> </div> ); } |
As you can see we have the simple
input field where we are taking the input
from the user which is the url
of the youtube video and then we have the input
field where we are embeding the video using the videoid
parameter. And then we are displaying it inside the youtube video player
and also we have autoplay
options as well.