How to set Infinite Scroll in React Js

Posted By : Rajan Rawat | 09-May-2018

These days the infinite scrolling is become so much popular and use technique this will help you to load your web-page contents through the page without any pagination you can scroll down the page to load the new content. This technique attracts every developer and development team. But on the other side, I would say it hasn't replaced the pagination. Both techniques have their own features and use. If I talk about the infinite scrolling this is very good social media platforms and also for the search engines as well.

 

Now, let's go through the development of infinite scroll and I found two ways of it.

  • You make your manual plugin for this from scratch coding and doing all by yourself.
  • You can simply install the react js plugin of infinite scroll and use it. If you are going to this you can just download it from the internet.

Lets try it with the first way.

Listening the scroll event

for using the infinite scroll in react js is by listening the scroll event which is pre-defined or we can add the event on div or an object jus like the below code

render() {
    return (
      

My First React Infinite Scroll

); }

The above code will be simply has a ul tag with which we bind the fetched items and ul tag is surrounded by the div tag with which we attached the event listener which listen the scroll event.

 

Entire code

                class example extends React.Component {
  constructor(props) {
   super(props);
   this.state = {
      items: 10,
      loadingState: false
    };
  }

  componentDidMount() {
    this.refs.iScroll.addEventListener("scroll", () => {
      if (this.refs.iScroll.scrollTop + this.refs.iScroll.clientHeight >=this.refs.iScroll.scrollHeight){
        this.loadMoreItems();
      }
    });
  }

  displayItems() {
    var items = [];
    for (var i = 0; i < this.state.items; i++) {
      items.push(
  • Item {i}
  • ); } return items; } loadMoreItems() { this.setState({ loadingState: true }); setTimeout(() => { this.setState({ items: this.state.items + 10, loadingState: false }); }, 3000); } render() { return (
    • {this.displayItems()}
    {this.state.loadingState ?

    loading More Items..

    : ""}
    ); } }

now run above entire code in your component and you will see the desired results. I hope now you got real concept of infinite scroll.

About Author

Author Image
Rajan Rawat

Rajan is a UI Developer, having good knowledge of HTML, CSS and javascript. His hobbies are internet surfing and watching sports.

Request for Proposal

Name is required

Comment is required

Sending message..