Here is a cleaner version of the code above that compliance with Eslint.
There is a problem with the code . It'll add infinite number of elements without being triggered by scrolling to the end of the list.
importReact,{useEffect,useState,useRef}from'react'constdivStyle={color:'blue',height:'250px',textAlign:'center',padding:'5px 10px',background:'#eee',marginTop:'15px',}constcontainerStyle={maxWidth:'1280px',margin:'0 auto',}exportfunctionInfiniteScroll(){const[postList,setPostList]=useState({list:[1,2,3,4]})// tracking on which page we currently areconst[page,setPage]=useState(1)// add loader referenceconstloader=useRef(null)// here we handle what happens when user scrolls to Load More div// in this case we just update page variableconsthandleObserver=(entities)=>{consttarget=entities[0]if(target.isIntersecting){setPage(_page=>_page+1)}}useEffect(()=>{constoptions={root:null,rootMargin:'20px',threshold:1.0,}// initialize IntersectionObserver and attaching to Load More divconstobserver=newIntersectionObserver(handleObserver,options)if(loader.current){observer.observe(loader.current)}},[])useEffect(()=>{// here we simulate adding new posts to ListconstnewList=postList.list.concat([1,1,1,1])setPostList({list:newList,})},[page,postList.list])return(<divclassName="container"style={containerStyle}><divclassName="post-list">{postList.list.map((post,index)=>(<divkey={index}className="post"style={divStyle}><h2>{post}</h2>
</div>
))}<divclassName="loading"ref={loader}><h2>LoadMore</h2>
</div>
</div>
</div>
)}
Be carefull... that postList.list as dependencies will make your component enter an infinite loop of rerenders. It is better to access this property via an arrow function.
Here is a cleaner version of the code above that compliance with Eslint.
There is a problem with the code . It'll add infinite number of elements without being triggered by scrolling to the end of the list.
Be carefull... that
postList.list
as dependencies will make your component enter an infinite loop of rerenders. It is better to access this property via an arrow function.Also,
handleObserver
is better to be insde the useEffect function and you should clear (observer.unobserve) the listener on a callback funtion. ;)