Auto load React Components on Scroll

There are lots of npm packages or ready made react components that you can use. But if you want to customize that loading effect as you like it will be better to create your own. Because using a npm package will limit you to its features and functions. If you know how to load components properly on scroll it will be easier for you to adjust your code to meet client needs.

Lazy Loading

Lazy loading is a concept where we delay the loading of the object until the point where we need it. Loading all the data at once will take much time and as a result page load time increase. 40% of people abandon a website that takes more than 3 seconds to load so it is always better to take actions to reduce page load time. That may reduce customer satisfaction and loss of traffic to your site.

Lazy loading or delay loading content when needed is the solution. Because if you have long list of items loading all of them at once is not good. Because sometime users will have no interest in going through all the items even though all the items are loaded. Loading them when user requested is the best solution. Through that you can have good page loading time.

Lazy loading or Delay loading content using ReactJs

Today I am going to tell you to implement very simple auto loading data or components when scroll. No plugins or npm packages required. Just simple JavaScript with ReactJs.

Click here for Demo

Step 1: Set required states

this.state = {
  total:12,
  currentCount:3,
  offset:3,
  list:[],
  isFetching:false
}

Above states variables are used to update auto load list.

"total" - Total number of items in the list.
"currentCount" -  Current count in the list.
"offset" -  Number of items loads per request.
"list" - Array of items used to render. This is the array updated. When user scroll new items will be requested from server and added to this list.
"isFetching" - When there is an active server request to get items, value of this variable is "true"

Step 2: Add event listener to listen scroll

componentDidMount(){
  window.addEventListener('scroll', this.loadOnScroll);
}

Above code will add scroll event listener to react component. Every time user scroll it will trigger "loadOnScroll" function.

Step 3: Create "loadOnScroll" function.

loadOnScroll = (e) =>{
    //If all the content loaded
    if(this.state.currentCount == this.state.total) return;

    //Get div at the bottom of the content
    var el = document.getElementById('content-end');

    var rect = el.getBoundingClientRect();
    var isAtEnd = (
        // rect.top >= 0 &&
        // rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
    );

    //User at the end of content. load more content
    if(isAtEnd){
      //If content list is still loading do not request for another content list.
      if(this.state.isFetching) return
      this.setState({isFetching:true});

      //Call server and request content.
      /**
      * AJAX reuest
      */

      //On AJAX request success
      this.setState({isFetching:false});
      //Update content list
    }
  }

Here you can request server to load content. Request server function should be called when
- there is no active server requets
- all the items are not loaded.

Step 4 : Create rendering part

You can customize this part as you like. This is the place where users can really see content or items. I will show you basic one.

render() {
  return (
    <div>
      <div>
      {
        this.state.list.map((item,index) => (
          <div key ={index}>
              {/* render each item here */}
          </div>
        ))
      }
      
      { /* Start load more content when this div is visible*/
        (this.state.currentCount !== this.state.total)?
        <div id="content-end" >
          Please wait. Loading...
        </div>: null
      }
      </div>
    </div>
  );
}

Step 5: Set initial set of items

Set initial set of items visible to user. If not your page will be empty till user start to scroll.

componentWillMount(){
  this.loadInitialContent();
}

loadInitialContent(){
  //Get content from server using your preferred method (like AJAX, relay)
  //Update list array
}

Step 6: Remove scroll event listener

When component unmounted you should remove scroll event listener. If not it will keep listening to scroll event even though it is not used. This may create errors while using the app.

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

Example Source Code.

Click here to download source code.

Download Now

Check "src/app.js" for code example.

How to run example.

npm install
npm start

Add a Comment

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