Good question...!
So you need to do something like this:
constructor(props){
super(props);
this.state = {
data: [],
total:null,
currentCount:3,
offset:3,
};
this.loadOnScroll = this.loadOnScroll.bind(this);
this.loadInitialContent = this.loadInitialContent.bind(this);
}
componentDidMount () {
window.addEventListener('scroll', this.loadOnScroll);
}
componentWillMount(){
this.loadInitialContent();
}
loadInitialContent(){
fetch( APIurl , {
method: "GET",
headers: {
"Content-Type": "application/json"
},
credentials: "same-origin" })
.then(
response => response.json()
).then(
myData => {
let ary = myData.slice(0,this.state.offset)
this.setState({ data: ary, list: myData, total: myData.length });
}
)
}
componentWillUnmount(){
window.removeEventListener('scroll', this.loadOnScroll);
}
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');
if(el) {
var rect = el.getBoundingClientRect();
var isAtEnd = (
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});
var count = this.state.currentCount + this.state.offset
if(this.state.currentCount <= this.state.total){
this.setState({
isFetching:false,
currentCount:count,
data: this.state.list.slice(0, count)
})
}
}
}
render() {
return (
<section>
<div className="content">
your contents here ....
</div>
<div id="content-end" >
{ /* Start load more content when this div is visible*/
(this.state.currentCount <= this.state.total && this.state.isFetching)? <span>Loading Content...!!</span>
: null
}
</div>
</section>