Skip to content

How to detect page scroll to top in React.js?

I have a UI problem to solve in React. When the user start scroll, will add a background class to the header. When scrolling to the top of the page, header background disappear.

I have figure out how to add the background while scrolling and modify the state, but how to detect whenever user scroll to the top of the page?

Answer

You can do it by adding a listener window.onscroll and watch in this listener for window.pageYOffset. Here is the example https://codepen.io/teimurjan/pen/NzMgKz?#.