Last active
June 8, 2022 09:55
-
-
Save koistya/934a4e452b61017ad611 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; |
If anyone is thinking they are going crazy that it's not working for them, while everyone else is piling on saying it does, try this:
componentDidMount() { window.addEventListener('scroll', this.handleScroll, true); }
Note, the third argument of "true".
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
Worked for me
thank you very much @paintedbicycle
This worked for me:
constructor(props) { super(props); this.handleScroll = this.handleScroll.bind(this); } componentDidMount() { window.addEventListener('scroll', this.handleScroll); }; componentWillUnmount() { window.removeEventListener('scroll', this.handleScroll); }; handleScroll(event) { console.log('the scroll things', event) };
your solution worked for me. Thank you for this
@raheemazeezabiodun Note, that if you use an arrow function syntax for declaring custom handlers, you won't need to bind them to this
inside of a constructor function:
constructor(props) {
supert(props);
this.handleScroll = this.handleScroll.bind(this);
}
handleScroll(event) { ... };
vs
handleScroll = (event) => { ... };
Is anyone having issues with the event returning as undefined?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks this is exactly what I needed to do for a ShadowDOM supported div that used
onScroll
.Turns out ShadowDOM does not support
scroll
listener, it's essentially blocked.What I did was:
and it worked! 🎉