How to embed a Youtube video in React

#react

Last updated on Dec 2, 2020 by Suraj Sharma



In this tutorial, you will learn to embed a Youtube video using youtube URL in your React application using a react-player npm module.



Getting started


Assume you have an existing React application where you want to embed a Youtube video.


Install react-player npm module


npm install --save react-player

OR

yarn add react-player


Embed a Video using Youtube URL


Create a function component <EmbedVideo />, which imports react-player and takes a youtube URL to embed on your application

./EmbedVideo.jsx

import ReactPlayer from 'react-player/youtube';
// or
// import ReactPlayer from 'react-player';
//if you want to support other video URLs

const EmbedVideo = (props) => {
  return (
    <ReactPlayer url={props.url} />
  );
}

export default EmbedVideo;


Now, import and test it in App.jsx file



const App = () => {

  return (
    <EmbedVideo url="https://www.youtube.com/watch?v=4_4Llj0aiNo" />
  );
}

export default App;


After your react application reloads, you see something similar to this on your browser


Embed youtube video using react-player



For more advanced react-playerexamples and demo, visit react-player demo



Related Solutions



Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.