Created
April 26, 2019 13:33
-
-
Save ivansky/4cda745db621e274a6dfb79594fbf7b1 to your computer and use it in GitHub Desktop.
React how to attach scroll event and measure DOM elements
This file contains hidden or 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 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