Reputation: 4318
I've tried looking around for examples but all i have is youtube-react
npm
packages which I don't want since I want to do it and learn it myself.
My issue is on the docs here: https://developers.google.com/youtube/iframe_api_reference It tells me to provide an anchor tag for Google to append the iFrame depending on what you pass it.
However, I have react on the server-side and use web-pack to compile it to the client-side my react component so far looks like :
import React from 'react';
import { Link } from 'react-router'
import classnames from 'classnames'
const videoId = 'XxVg_s8xAms';
export default React.createClass({
getInitialState: function() {
return {
YTid: videoId,
}
},
render() {
return (
<section className="youtubeComponent-wrapper">
<div id="youtubePlayerAnchor"></div>
</section>
)
}
})
I've tried adding the code from the developer docs into a script
tag onto the client but nothing happens nothing in console nothing.
Is there any resources or could anyone point me in the right direction on how i'd go about handling this.
Thanks!
Upvotes: 1
Views: 6038
Reputation: 17168
You could probably create a React component like this:
import { Component, PropTypes } from 'react'
let loadYT
export default class YouTube extends Component {
componentDidMount () {
if (!loadYT) {
loadYT = new Promise((resolve) => {
const tag = document.createElement('script')
tag.src = 'https://www.youtube.com/iframe_api'
const firstScriptTag = document.getElementsByTagName('script')[0]
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag)
window.onYouTubeIframeAPIReady = () => resolve(window.YT)
})
}
loadYT.then((YT) => {
this.player = new YT.Player(this.youtubePlayerAnchor, {
height: this.props.height || 390,
width: this.props.width || 640,
videoId: this.props.YTid,
events: {
onStateChange: this.onPlayerStateChange
}
})
})
}
onPlayerStateChange = (e) => {
if (typeof this.props.onStateChange === 'function') {
this.props.onStateChange(e)
}
}
render () {
return (
<section className='youtubeComponent-wrapper'>
<div ref={(r) => { this.youtubePlayerAnchor = r }}></div>
</section>
)
}
}
YouTube.propTypes = {
YTid: PropTypes.string.required,
width: PropTypes.number,
height: PropTypes.number,
onStateChange: PropTypes.func
}
Upvotes: 15