I would highly recommend adding an extra check to your condition. When you scroll a single-time, you update your component-state multiple times after a certain range (100), which is unnecessary. You only need to update it once.
It will keep updating because you meet the condition inside handleScroll, even though the background has already changed. The sheer amount of updates can cause your app to crash.
Try something like this it will update your component-state as expected and only when necessary: https://codesandbox.io/s/white-architecture-jepyc
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
navBckgroundColor: `blue`,
altered: false
};
}
componentDidMount() {
window.addEventListener("scroll", this.handleScroll);
}
//use arrow function instead so that its "this" keyword points to the component's execution context. Otherwise, "this" will point to the global window object where you cannot use this.setState.
handleScroll = e => {
if (window.pageYOffset > 100 && !this.state.altered) {
this.setState({
navBckgroundColor: `red`,
altered: true
});
} else if(window.pageYOffset < 100 && this.state.altered) {
this.setState({
navBckgroundColor: `blue`,
altered: false
});
}
};
render() {
return (
<div className="App">
<Navbar bckGroundColor={this.state.navBckgroundColor} />
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
}