Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
progress bar
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
You can’t perform that action at this time.