Skip to content

Instantly share code, notes, and snippets.

@jherax
Forked from koistya/App.js
Last active October 23, 2023 01:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jherax/7bb286c0fbed9c4f852198fcab54ba27 to your computer and use it in GitHub Desktop.
Save jherax/7bb286c0fbed9c4f852198fcab54ba27 to your computer and use it in GitHub Desktop.
How to add `onscroll` event with requestAnimationFrame in ReactJS component
import React from 'react';
let lastScrollY = 0;
let ticking = false;
class App extends React.Component {
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
}
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