Kirk Ross Kirk Ross - 1 year ago 163
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 {

console.log('Scroll start');

console.log('Scroll end 300ms(default)');
scrollListener.addScrollHandler('body', myScrollStartHandler, myScrollEndHandler );
return <StaticImageList />;

export default Album;

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download