I'm building an app (ES6) and I'm curious what is the 'correct' way to catch scroll up / down events?
I tried (npm) installing react-scroll-listener but I couldn't get it to work with my ES6 class.
Basically I want: if scroll up, do this; if scroll down, do something else.
import React from 'react';
import config from '../config';
import StaticImageList from '../Common/StaticImageList';
import ScrollListener from 'react-scroll-listener';
class Album extends React.Component {
constructor(props){
super(props);
}
myScrollStartHandler(){
console.log('Scroll start');
}
myScrollEndHandler(){
console.log('Scroll end 300ms(default)');
}
componentDidMount(){
scrollListener.addScrollHandler('body', myScrollStartHandler, myScrollEndHandler );
}
render(){
return <StaticImageList />;
}
};
export default Album;
This is general advice for hooking into any listeners:
Attach stuff in
componentDidMount
, unattach incomponentWillUnmount
Actually there are many ways to do it, but using React hooks was the easier one for me, all you need to do is:
Something like:
Now you have scrollPosition in pixels to work on
In this particular case useEffect will be equivalent to componentDidMount because it will be fired once the component mounts, but also after all updates, but
addEventListener
is smart enough to not start duplicated listeners.The return inside of useEffect is equivalent to componentWillUnmount, it'll "called" when the component unmounts.