React: DOM trigger events for pagination

We will explore how we can leverage DOM events to achieve pagination by scrolling.

1) End of a page

When a user scrolls down to the bottom of a web page, a DOM event can be triggered. Below shows an example of how we can associate the event with a React Component.

class DOMEventExample extends React.Component {
  constructor(props) {
    super(props)    
  }
  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll);
  }
  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll);
  }
  handleScroll = (event) => { console.log(event); }
  render() { ... }
}

2) End of a div element

In this example we respond to a user that scrolls down to the end of a <div> element, we will hook up code to this event and achieve end-of-div scrolling.

For this to work, the div must have finite height or width (if scrolling horizontally). The div element will need to release the scroll bars to accommodate content that has overflow.

const styles = createStyles(theme => ({
  example: {
    height: '85vh', overflowY: 'auto'
  }
}));

const Scrollable = withStyles(styles)((props) => {
  const classes = props.classes;
  const onScroll = (e) => {
    const bottom = Math.ceil(e.target.scrollTop) === e.target.scrollHeight - e.target.clientHeight;
    if (bottom) {
      console.log('load more stuff')
    }
  }
  return (<Grid className={classes.example} onScroll={onScroll}></Grid>)
});