0

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

1
  • try checking scroll position and then fetch your next data! you can use this react-scroll library : npmjs.com/package/react-scroll Commented Jul 23, 2019 at 11:47

1 Answer 1

2

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...
        }
    };
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for reply, here I want to know why have put 50, please can you tell me .
Because every time the answer of this equation is not equal to zero so the condition will not true so i put less than 50 it means the scroll is almost move to bottom here is the equation : (e.target.scrollHeight - e.target.scrollTop).toFixed(0)) - e.target.clientHeight
ok, Great explanation, a little issue, if my scroll height is 200px and initially I am displaying 5 record which height is less the 200 px so in that case scroll will not be visible and I won't able to fetch rest data.
i think you should decrease the height so that scroll will enable otherwise if scroll will not enable onScroll event will not triggered.
or load 10 record initially so that scroll enabled.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.