Skip to content

Instantly share code, notes, and snippets.

@gustavonovaes
Last active February 11, 2019 20:51
Show Gist options
  • Save gustavonovaes/7341798db71b2727f2228fc428391132 to your computer and use it in GitHub Desktop.
Save gustavonovaes/7341798db71b2727f2228fc428391132 to your computer and use it in GitHub Desktop.
Component that shows the progress of scroll on top of page
import React from 'react'
const ProgressBar = ({ height, color, progress }) => {
const containerStyle = {
position: 'fixed',
top: 0,
left: 0,
padding: 0,
margin: 0,
width: '100%',
color: '#666666',
backgroundColor: '#f4f6f9',
border: 'solid 1px lightgray',
height: height,
zIndex: '9999'
}
const progressStyle = {
width: `${progress}%`,
height,
backgroundColor: color || '#5a9eea'
}
return (
<div style={containerStyle}>
<div style={progressStyle} />
</div>
)
}
class ScrollProgress extends React.Component {
state = {
scrollY: 0,
scrollRate: 0
};
recalculateScrollRate = () => {
const scrollY = document.documentElement.scrollTop
const scrollMax = Math.ceil(document.documentElement.scrollHeight - document.documentElement.clientHeight)
const scrollRate = parseInt((scrollY / scrollMax) * 100, 10);
this.setState({
scrollY: scrollY,
scrollRate: scrollRate
});
}
componentDidMount = () => {
document.addEventListener('scroll', this.recalculateScrollRate);
window.addEventListener('hashchange', this.recalculateScrollRate);
this.recalculateScrollRate();
}
componentWillUnmount = () => {
document.removeEventListener('scroll', this.recalculateScrollRate);
window.removeEventListener('hashchange', this.recalculateScrollRate);
}
render() {
const { height } = this.props
const { scrollRate } = this.state
return <div>
{scrollRate > 0 && <ProgressBar height={height} color="#5a9eea" progress={scrollRate} />}
</div>
}
}
export default ScrollProgress
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment