Last active
January 30, 2020 13:26
-
-
Save zoetrope69/b227b10c2206162e4e91c517704fc029 to your computer and use it in GitHub Desktop.
Simplified YouTube React iFrame with Embed Config
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'; | |
import PropTypes from 'prop-types'; | |
import querystring from 'qs'; | |
const isYouTubeEmbedURL = url => | |
!!url.match(/^(https|http):\/\/(?:www\.)?youtube.com\/embed\/[A-z0-9]+/g); | |
const getYouTubeVideoId = url => { | |
const match = url.match(/\/embed\/([^?]+)/); | |
return match[1]; | |
}; | |
const createYouTubeURLWithEmbedConfig = url => { | |
const adUnitPath = '12345/ExampleAdUnit/Youtube-PFP'; | |
const keyValuePairs = { | |
kvid: getYouTubeVideoId(url) | |
}; | |
// Key-values processed as a URL string, as we would do for VAST tags | |
const keyValuePairsParams = querystring.stringify(keyValuePairs, { | |
arrayFormat: 'comma', | |
encode: false | |
}); | |
const embedConfig = { | |
adsConfig: { | |
adTagParameters: { | |
iu: adUnitPath, | |
cust_params: keyValuePairsParams | |
}, | |
nonPersonalizedAd: false | |
} | |
}; | |
const embedConfigParam = encodeURIComponent(JSON.stringify(embedConfig)); | |
return `${url}?embed_config=${embedConfigParam}`; | |
}; | |
const ExampleYouTubeiFrame = ({ url }) => { | |
if (!url || !isYouTubeEmbedURL(url)) { | |
return null; | |
} | |
return ( | |
<iframe | |
title="YouTube Player" | |
width="560" | |
height="315" | |
src={createYouTubeURLWithEmbedConfig(url)} | |
frameBorder="0" | |
allow="autoplay; encrypted-media" | |
allowFullScreen | |
/> | |
); | |
}; | |
ExampleYouTubeiFrame.propTypes = { | |
url: PropTypes.string.isRequired | |
}; | |
export default ExampleYouTubeiFrame; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment