React.js Youtube Video Embed as a IFrame Using React-Youtube and get-youtube-id Library Full App

React.js Youtube Video Embed as a IFrame Using React-Youtube and get-youtube-id Library Full App

 

Welcome folks today in this post I will be talking about How to embed Youtube Video as iframe in react app Using react-youtube and get-youtube-id library. All the source code of the application is given below. A step by step youtube video is also shown below.

 

 

 

Get Started

 

Install these two dependencies to get started

 

npm i react-youtube

 

npm i get-youtube-id

 

After this make a index.js file and copy paste the following code inside it.

 

import React, { useState } from "react";
import "./styles.css";
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>
  );
}

 

 

Here we are embed youtube video inside react app by passing a configuration object holding the width and height of the video and also the autoplay parameter.

See also  jsPDF Html2Canvas.js Tutorial to Export Google Maps Image to PDF Document in Browser Using Javascript Full Project For Beginners

And after that inside the html we have a input field in which user enters the youtube url for which it needs to embed inside the app after the value changes a callback function fires handlechange and automatically it fetches the youtube video by converting the passed youtube url and extracts only the youtube id from it by using the get-youtube-id dependency and after that it sets the id by using the hooks method setId and lastly we display the video using the react-youtube library.

 

 

Leave a Reply