I should create an infinite scroll in reactJs having a JSON with data in it. Could you help me?
I would like to do it from scratch and not with some library
{data?.map((conto) => {
return (
<Suspense key={conto._uid} fallback={<p>Loading...</p>}>
<Conto blok={conto} data={data} ITEuro={ITEuro} deposit={deposit} handleToggleFavourite={handleToggleFavourite} isFavourited={isFavourited} depositQuantity={depositQuantity} />
</Suspense>
)
})}
I load the JSON like this for now, but I would like a maximum number of ids to be loaded until we reach the bottom of the page and more are loaded
2
Answers
I managed to solve it this way
Here’s a sample implementation of the infinite scroll:
In this implementation,
jsonData
represents your complete JSON data. We start by loading the first ten items initially, and then, as the user scrolls down and reaches the bottom of the container (div
withref={containerRef}
), we load ten more items until we have loaded all the data. Make sure to replace the comment inside the.map()
function with your actual rendering of theConto
component with the appropriate props.Remember to adjust the number of items to load at once or tweak the behavior according to your specific use case. Also, note that the code assumes that your
Conto
component is renderable using theSuspense
component. If you’re using asynchronous components, it’s essential to wrap them withSuspense
.Edit:
In this revised implementation, I’ve added
loadedItems
to the dependency array of theuseEffect
hook. This means that the event listener will be reattached whenever the value ofloadedItems
changes. By doing this, we ensure that thehandleScroll
function is aware of the updatedloadedItems
value and will trigger the loading of more items correctly when the user reaches the bottom of the container.This should resolve the issue, and the code should now load more items as you scroll to the bottom of the page.
Edit 2:
I finally figured it out. In the
handleScroll
function, the condition to check whether the user has reached the bottom should use the less than or equal to<=
operator instead of just the equal to===
operator. This change will ensure that theloadMoreItems
function is triggered when the user is very close to the bottom of the container, not just at the exact pixel when the height matches.I’ve also added inline styles to the container div to specify its height and allow vertical scrolling so that the infinite scroll works as expected.