Created
January 18, 2019 09:51
-
-
Save JaeYeopHan/c4be75fcc51d87a6f28b9f22e18b60db to your computer and use it in GitHub Desktop.
progress bar
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 { throttle } from 'lodash-es' | |
import './index.scss' | |
export class ProgressBar extends React.Component { | |
constructor(props) { | |
super(props) | |
this.state = { | |
scrollY: 0, | |
scrollBarRate: 0, | |
} | |
this.ScrollRateCalculation = this.ScrollRateCalculation.bind(this) | |
} | |
ScrollRateCalculation() { | |
let innerHeight = window.innerHeight //A | |
let bodyElement = document.body | |
let rect = bodyElement.getBoundingClientRect() //B2 | |
let heightIsHtml = rect.height //B3 | |
let scrollMax = Math.ceil(heightIsHtml - innerHeight) //C = B3 - A | |
let scrollY = document.documentElement.scrollTop || document.body.scrollTop //D | |
let scrollRate = parseInt((scrollY / scrollMax) * 100, 10) //E = (D / C) *100 | |
this.setState(() => ({ | |
scrollY: scrollY, | |
scrollBarRate: scrollRate, | |
})) | |
} | |
componentDidMount() { | |
this.ScrollRateCalculation() | |
document.addEventListener( | |
'scroll', | |
throttle(this.ScrollRateCalculation), | |
300 | |
) | |
window.addEventListener('hashchange', this.ScrollRateCalculation) | |
} | |
componentWillUnmount() { | |
document.removeEventListener('scroll', this.ScrollRateCalculation) | |
window.removeEventListener('hashchange', this.ScrollRateCalculation) | |
} | |
render() { | |
return ( | |
<div className="progress-bar"> | |
<div | |
className="progress-bar status" | |
id="hoge" | |
style={{ | |
width: `${this.state.scrollBarRate}%`, | |
}} | |
/> | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment