Scroll Events in React

Scroll Events in React.

Scroll Events in React

When a user scrolls a DOM scroll event is fired, an event which is built into every browser by default. React has it’s own method, onScroll, which can be called on any component when the scroll event is fired. Using this onScroll method we can call a function as a result of a user scrolling.

Example;

<SomeComponent onScroll={someMeothod} />

As with any DOM event, an event object is created with properties that can provide useful information about the event and the element said event is related too. A scroll event is fired for every pixel a user scrolls. In this case, we are only concerned with identifying when the user has scrolled to the end of the parent element containing our content.

Calculating when user has scrolled to end of a container

Add an onScroll method to element containing content which calls a function on the components class:

<div className="content-container" onScroll={this.handleScroll}>
  // Your content
</div>

Then create the handleScroll function to handle the scroll event:

class MyComponent extends React.Component {
  handleScroll = e => {
    let element = e.target
    if (element.scrollHeight - element.scrollTop === element.clientHeight) {
      // do something at end of scroll
    }
  }
  render() {
    return (
      <div className="content-container" onScroll={this.handleScroll}>
        // Your content
      </div>
    )
  }
}