Skip to content
Advertisement

Toggle Class based on scroll React JS

I’m using bootstrap 4 nav bar and would like to change the background color after ig 400px down scroll down. I was looking at the react docs and found a onScroll but couldn’t find that much info on it. So far I have…

I don’t know if I’m using the right event listener or how to set the height etc.

And I’m not really setting inline styles…

JavaScript

Advertisement

Answer

One way to add a scroll listener is to use the componentDidMount() lifecycle method. Following example should give you an idea:

JavaScript

This changes the Text from “Scroll down” to “Scroll up” when your scrollY position is at 100 and above.

Edit: Should avoid the overkill of updating the state on each scroll. Only update it when the boolean value changes.

Advertisement