Last active
September 7, 2019 17:01
-
-
Save xdmorgan/21c1b427d76bf432cf647e57716dcacd to your computer and use it in GitHub Desktop.
React YouTube Embed Component (iframe)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
export default function YouTubeEmbed({ videoId, ...props }) { | |
return ( | |
<iframe | |
width="560" | |
height="315" | |
src={idToEmbedURL({ id: videoId })} | |
frameborder="0" | |
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" | |
allowfullscreen="true" | |
{...props} | |
/> | |
) | |
} | |
const bool2num = bool => (bool ? 1 : 0) | |
// via https://developers.google.com/youtube/player_parameters | |
function idToEmbedURL({ | |
id, | |
rel = false, | |
autoplay = false, | |
modest = true, | |
base = 'https://www.youtube.com/embed', | |
}) { | |
const params = { | |
autoplay: `autoplay=${bool2num(autoplay)}`, | |
branding: `modestbranding=${bool2num(modest)}`, | |
rel: `rel=${bool2num(rel)}`, | |
} | |
const opts = Object.values(params) | |
.map(v => v) | |
.join('&') | |
return `${base}/${id}?${opts}` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example