-
-
Save codeibrahima/80fb2bd515b8c2633d3fd25b90f0f5a5 to your computer and use it in GitHub Desktop.
How to add `onscroll` event in ReactJS component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
let lastScrollY = 0; | |
let ticking = false; | |
class App extends React.Component { | |
componentDidMount() { | |
window.addEventListener('scroll', this.handleScroll, true); | |
} | |
componentWillUnmount() { | |
window.removeEventListener('scroll', this.handleScroll); | |
} | |
nav = React.createRef(); | |
handleScroll = () => { | |
lastScrollY = window.scrollY; | |
if (!ticking) { | |
window.requestAnimationFrame(() => { | |
this.nav.current.style.top = `${lastScrollY}px`; | |
ticking = false; | |
}); | |
ticking = true; | |
} | |
}; | |
render() { | |
return ( | |
<div> | |
<nav ref={this.nav}> | |
</nav> | |
<div> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment