Skip to content

Instantly share code, notes, and snippets.

@ivansky
Created April 26, 2019 13:33
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 ivansky/4cda745db621e274a6dfb79594fbf7b1 to your computer and use it in GitHub Desktop.
Save ivansky/4cda745db621e274a6dfb79594fbf7b1 to your computer and use it in GitHub Desktop.
React how to attach scroll event and measure DOM elements
import throttle from 'lodash/throttle';
class Component {
someSectionRef = null;
componentDidMount() {
// check window object existing, to not listen events in SSR
if(window) {
window.addEventListener('scroll', this.onScroll);
}
}
componentWillUnmount() {
if(window) {
window.removeEventListener('scroll', this.onScroll);
}
}
// throttle 20ms to reduce calls and reflow
// see: https://gist.github.com/paulirish/5d52fb081b3570c81e3a
onScroll = throttle(() => {
// calculate window and section `this.someSectionRef` position
// some logic
}, 20);
render() {
return (
<div>
<div ref={ node => this.someSectionRef = node } />
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment