Skip to content

Instantly share code, notes, and snippets.

@btnwtn
Created September 26, 2016 19:12
Show Gist options
  • Save btnwtn/e22179512853af8f6c41fe4a750687c2 to your computer and use it in GitHub Desktop.
Save btnwtn/e22179512853af8f6c41fe4a750687c2 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react'
import YouTube from 'react-youtube'
export default class Video extends Component {
constructor(props) {
super(props)
this.state = {
progress: 0,
duration: 0,
player: null,
interval: null,
}
this.onReady = this.onReady.bind(this)
this.trackState = this.trackState.bind(this)
this.trackProgress = this.trackProgress.bind(this)
}
componentWillUnmount() {
console.log('Unmounting component')
window.clearInterval(this.interval)
}
onReady(event) {
this.setState({
duration: event.target.getDuration(),
player: event.target,
interval: window.setInterval(this.trackProgress, 1000),
})
}
trackProgress() {
const currentTime = this.state.player.getCurrentTime()
const duration = this.state.duration
const currentProgress = (Math.ceil(currentTime) / duration) * 100
if (currentProgress !== this.state.progress) {
this.setState({
progress: Math.ceil(currentProgress),
})
}
}
trackState(event) {
// todo: dataLayer stuff
switch (event.data) {
case YouTube.PlayerState.PLAYING:
console.log('playing')
break
case YouTube.PlayerState.ENDED:
console.log('ended')
// is clearing the interval in state necessary here?
window.clearInterval(this.state.interval)
this.setState({
interval: null,
progress: 100,
})
break
case YouTube.PlayerState.BUFFERING:
console.log('buffering')
break
case YouTube.PlayerState.UNSTARTED:
console.log('video loaded')
break
case YouTube.PlayerState.PAUSED:
console.log('video paused')
break
}
}
render() {
return (
<div>
<h4>Progress: {this.state.progress}%</h4>
<div className="responsive-embed bg-black">
<YouTube
videoId={this.props.youtubeId}
opts={{
playerVars: {
autoplay: 1,
rel: 0
}
}}
onReady={this.onReady}
onStateChange={this.trackState}
/>
</div>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment