How to create infinite scroll API call in reactjs

Infinite scroll means we want data to be loaded endlessly, when we are at the end of the scroll next data will load automatically.  for example, if you check Facebook posts it always loads when you scroll the page just like that.

We can also achieve this type of mechanism in our react application.

Step 1: You need to create one ref variable in your constructor.

constructor(props){
super(props);
this.loadingRef=React.createRef();
}

 

Step 2: After creating a ref variable, We need to add one empty div at the end of your rendering section (like after .map execution).
<div ref={this.loadingRef} ></div>
Step 3: After add ref div on their position. we are going to create an observer for the scroll event trigger. We can put it in a componentDidMount life cycle method.
componentDidMount(){
var options = {
        root: null,
        rootMargin: “80px”,
        threshold: 1.0
      };
      this.observer = new IntersectionObserver(
        this.handleObserver.bind(this),
        options
      );
      this.observer.observe(this.loadingRef.current);
}
  • root : This is the root to use for the intersection.
  • rootMargin : Just like a margin property, which is used to provide the margin value to the root either in pixel or in percent (%) .
  • threshold : The number which is used to trigger the callback once the intersection’s area changes to be greater than or equal to the value we have provided in this example
Step 4: After observer creation creates a handler method.
constructor(props){
        super(props)
        this.state={
            data:[],
            loading: false,
            page: 1,
            prevY: 0,
        }
        this.loadingRef=React.createRef();
    }
handleObserver=(entities, observer) => {
      const y = entities[0].boundingClientRect.y;
      if (this.state.prevY > y) {
            const lastData = this.state.books[this.state.books.length – 1];
 const curPage = this.state.page+1;
this.setState({ …this.state,prevY: y, page});
            //make you api call heare
         }
     this.setState({ …this.state,prevY: y });
    }

 

Now you are ready to make your component with infinite scroll.

Leave a Reply

Your email address will not be published. Required fields are marked *