Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 245
Dr.Dean Avatar asked Jun 22 '18 02:06

Dr.Dean


3 Answers

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

like image 67
teimurjan Avatar answered Oct 19 '22 09:10

teimurjan


const handleScroll = (e: React.UIEvent<HTMLElement>) => {
    if(e.currentTarget.scrollTop === 0) {
       alert("on top")
    }
} 
<div onScroll={handleScroll}>
       
</div>
like image 39
LeulAria Avatar answered Oct 19 '22 11:10

LeulAria


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>
like image 2
Behemoth Avatar answered Oct 19 '22 10:10

Behemoth