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?
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?#.
const handleScroll = (e: React.UIEvent<HTMLElement>) => {
if(e.currentTarget.scrollTop === 0) {
alert("on top")
}
}
<div onScroll={handleScroll}>
</div>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With