Skip to content

Instantly share code, notes, and snippets.

@xdmorgan
Last active September 7, 2019 17:01
Show Gist options
  • Save xdmorgan/21c1b427d76bf432cf647e57716dcacd to your computer and use it in GitHub Desktop.
Save xdmorgan/21c1b427d76bf432cf647e57716dcacd to your computer and use it in GitHub Desktop.
React YouTube Embed Component (iframe)
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}`
}
@xdmorgan
Copy link
Author

xdmorgan commented Sep 7, 2019

Example

const url2id = url => (rgx => rgx ? rgx[1] : '')(url.match(/v=(\w+)/))

function Video({ src = "https://www.youtube.com/watch?v=DXwTF_yoOrg" }){
    return <div className="..."><YouTubeEmbed videoId={url2id(src)} /></div>
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment