Kirk Ross Kirk Ross - 3 months ago 18
React JSX Question

React—listen for scroll up / down?

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;

Answer

This is general advice for hooking into any listeners:

Attach stuff in componentDidMount, unattach in componentWillUnmount

class Whatever extends Component {
  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll)
  }

  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll)
  }

  handlScroll(event) {
    // do something like call `this.setState`
    // access window.scrollY etc
  })
}