Ad

How To Load More Content From Server On Scroll In Reactjs

- 1 answer

I want to call API and load more item from database using scroll, initially, I want to display five record only, then if user scroll and reach bottom of scroll then I want to display five more record. it is about to lazy loading. Please I am new to reactjs how can I achieve it.

this is the my code.

{this.state.selected ==='text' && <div   style={{overflow:'auto', height:'200px'}}  data-tab-content="tab2">
                                                    {this.state.textList.length>0 ? this.state.textList.map(text=>
                                                   <p  >{text.text} </p>
                                                   ):<p>no record found</p>} */}

                                                   </div>}

Here I am making

// get Text List
getTextList(){
    debugger
    fetch(baseUrl +`/language/listtext/${'1'}/${'5'}/${this.state.lesson_id}/${this.state.premiumprice_id}`)
    .then(response => response.json())

        .then(data => {
            debugger
          if(data.status ===200){
            debugger
            this.setState({
                textList: data.text.docs,
            })
          }else{
            this.setState({textList : []})
          }


        })
}

Thank in advance

Ad

Answer

Add onScroll event on div like

// for example <div onScroll={this.handleScroll}/>
handleScroll = (e) => {
        const bottom = Number((e.target.scrollHeight - e.target.scrollTop).toFixed(0)) - e.target.clientHeight < 50;
        let page = this.state.page;
        if (bottom) {
            // write fetching logic here...
        }
    };
Ad
source: stackoverflow.com
Ad