Having an issue with the scrolling progress bar that seems to be stuck in the middle and moving in both directions, which doesn't look visually appealing. Can anyone suggest how to resolve this? Interestingly, the same code works fine on online editors but not in my VSCode.
Here's the code snippet:
import React from 'react';
class Progress extends React.Component {
constructor(props) {
super(props);
this.state = {
scrolled: 0,
};
}
componentDidMount() {
window.addEventListener('scroll', this.scrollProgress);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.scrollProgress);
}
scrollProgress = () => {
const scrollPx = document.body.scrollTop || document.documentElement.scrollTop;
const winHeightPx = document.documentElement.scrollHeight - document.documentElement.clientHeight;
const scrolled = `${(scrollPx / winHeightPx) * 100}%`;
this.setState({
scrolled: scrolled,
});
};
render() {
const progressContainerStyle = {
background: 'transparent',
height: '15px',
position: 'fixed',
top: 0,
left: 0,
width: '100vw',
zIndex: 100,
};
const progressBarStyle = {
height: '15px',
backgroundImage: 'linear-gradient(-90deg, #6098df, #b581b0)',
width: this.state.scrolled,
};
return (
<div className="progress-container" style={progressContainerStyle}>
<div className="progress-bar" style={progressBarStyle} />
</div>
);
}
}
export default Progress;