11

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?

Dr.Dean
  • 149
  • 1
  • 1
  • 5
  • Check this: [https://stackoverflow.com/questions/45585542/detecting-when-user-scrolls-to-bottom-of-div-with-react-js](https://stackoverflow.com/questions/45585542/detecting-when-user-scrolls-to-bottom-of-div-with-react-js) – Nada Ghanem Jun 22 '18 at 02:40

3 Answers3

16

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?#.

teimurjan
  • 1,875
  • 9
  • 18
4

Here's another version using React Hooks and Functional Components:

const App = () => {
  React.useEffect(() => {
    window.onscroll = () =>
      window.pageYOffset === 0 && console.log("back at top");

    return () => (window.onscroll = null);
  });

  return <div className="container">I'm a very large box</div>;
};

ReactDOM.render(<App />, document.getElementById("root"));
.container {
  height: 500px;
  background-color: blue;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 4em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Behemoth
  • 5,389
  • 4
  • 16
  • 40
3
const handleScroll = (e: React.UIEvent<HTMLElement>) => {
    if(e.currentTarget.scrollTop === 0) {
       alert("on top")
    }
} 
<div onScroll={handleScroll}>
       
</div>
JulienRioux
  • 2,853
  • 2
  • 24
  • 37
LeulAria
  • 333
  • 3
  • 9