How to load and play a Youtube video in React

Viewed 7456

Currently I am trying to build an app that should include a YouTube link "https:\/\/www.youtube.com\/watch?v=IEDEtZ4UVtI". So the first attempt to run this is O<video className="video" src="https:\/\/www.youtube.com\/watch?v=IEDEtZ4UVtI"></video>, but as you might see it would not work as it should suppose to be. What are the other options. Keep in mind I don't have any embedded links in my API, so the first YouTube link you see only one that I should use.

2 Answers

Earlier it was possible to embed Youtube videos like this:

<video controls="true">
    <source src="www.youtube.com/watch?v=IEDEtZ4UVtI" type="video/mp4">
</video>

...but not anymore.

The only option is to use the usual iframe embedding, which works nicely with React apps. You just need to use the Youtube video ID from the link you have and us it in the embed link https://youtube.com/embed/${youtubeID}?autoplay=0.

const [youtubeID] = useState('IEDEtZ4UVtI')

[...]

<iframe className='video'
        title='Youtube player'
        sandbox='allow-same-origin allow-forms allow-popups allow-scripts allow-presentation'
        src={`https://youtube.com/embed/${youtubeID}?autoplay=0`}>
</iframe>

There is an easy way;

First of all install:

$ npm install react-youtube

import:

import YouTube from 'react-youtube';

and the usage-

<YouTube videoId="IEDEtZ4UVtI"/>

You can see more options for react-youtube here

Related