Frontend employee
Frontend employee

Reputation: 729

How to load and play a Youtube video in React

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.

Upvotes: 7

Views: 30665

Answers (4)

theDavidBarton
theDavidBarton

Reputation: 8841

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 use 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>

Upvotes: 10

Viraj Vhatkar
Viraj Vhatkar

Reputation: 1

The videoId property of the YouTube component should be the actual ID of the YouTube video, not the full URL.

Upvotes: 0

Fotios Tsakiris
Fotios Tsakiris

Reputation: 1556

You can use react-player

npm i react-player

import ReactPlayer from 'react-player/youtube'

 <ReactPlayer url='https://www.youtube.com/watch?v=IpYJjVw6wjU&ab_channel=fotios' />

docs

Upvotes: 3

Ruth
Ruth

Reputation: 124

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

Upvotes: 7

Related Questions