Tiempo de lectura: < 1 minutoToday we’re going to learn how we can add a YouTube video in React.
The first thing we need to do is to add this dependency:
npm install react-youtube --save
npm install react-youtube --save
npm install react-youtube --save
Once installed, let’s create the component responsible for opening the YouTube video.
We’ll call it YoutubePlayer.tsx
import React from 'react';
import YouTube, { YouTubeProps } from "react-youtube";
const YoutubePlayer: React.FC<Props> = ({ idYoutubeVideo }) => {
const opts: YouTubeProps['opts'] = {
const onPlayerReady: YouTubeProps['onReady'] = (event) => {
// access to player in all event handlers via event.target
event.target.pauseVideo();
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
<YouTube videoId={idYoutubeVideo} opts={opts} onReady={onPlayerReady} id="video" />
export default YoutubePlayer;
import React from 'react';
import YouTube, { YouTubeProps } from "react-youtube";
interface Props {
idYoutubeVideo: string;
}
const YoutubePlayer: React.FC<Props> = ({ idYoutubeVideo }) => {
const opts: YouTubeProps['opts'] = {
height: '390',
width: '640',
};
const onPlayerReady: YouTubeProps['onReady'] = (event) => {
// access to player in all event handlers via event.target
event.target.pauseVideo();
}
return (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
<YouTube videoId={idYoutubeVideo} opts={opts} onReady={onPlayerReady} id="video" />
</div>
);
};
export default YoutubePlayer;
import React from 'react';
import YouTube, { YouTubeProps } from "react-youtube";
interface Props {
idYoutubeVideo: string;
}
const YoutubePlayer: React.FC<Props> = ({ idYoutubeVideo }) => {
const opts: YouTubeProps['opts'] = {
height: '390',
width: '640',
};
const onPlayerReady: YouTubeProps['onReady'] = (event) => {
// access to player in all event handlers via event.target
event.target.pauseVideo();
}
return (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
<YouTube videoId={idYoutubeVideo} opts={opts} onReady={onPlayerReady} id="video" />
</div>
);
};
export default YoutubePlayer;
You can customize the options by adding playerVars: reference.
const opts: YouTubeProps['opts'] = {
// https://developers.google.com/youtube/player_parameters
const opts: YouTubeProps['opts'] = {
height: '390',
width: '640',
playerVars: {
// https://developers.google.com/youtube/player_parameters
//autoplay: 1,
},
};
const opts: YouTubeProps['opts'] = {
height: '390',
width: '640',
playerVars: {
// https://developers.google.com/youtube/player_parameters
//autoplay: 1,
},
};
And this is the result:
Post Views: 10
Related