meAndrew
meAndrew

Reputation: 309

React InfiniteScroll with Grid System

What is up, guys? I have an array of objects, I have Grid container, I map through array and render Grid items. Everything is ok, except all Grid cards get rendered at the same time and I have a long list. So, I decided to add infiniteScroll component. But still all cards got rendered at the same time. Here's what I return outta my component:

<>
      {pokemonData ? (
        <>
          <InfiniteScroll
            dataLength={pokemonData.length}
            next={handleChangePage}
            hasMore={true}
            loader={<h4>Loading...</h4>}
            endMessage={
              <p style={{ textAlign: "center" }}>
                <b>Yay! You have seen it all</b>
              </p>
            }
          >
            <Grid container spacing={4} className={classes.pokemonCardsArea}>
              {pokemonData.map(
                (pokemon, index) =>
                  pokemon.name.includes(searchInputValue) && renderCards(index)
              )}
            </Grid>
          </InfiniteScroll>
        </>
      ) : (
        <CircularProgress
          color={"success"}
          className={classes.progress}
          size={200}
        />
      )}
</>

handleChangePage function just sets up page state to page + 1; And I've got no errors, just a full list rendered and Loading... at the bottom of it. I didn't find any information about what excactly "next" function should be. But one guy made it setPage function, so I did the same. Everything works for him (he renders pictures, one in a row), but not for me, I guess because of grid system. Did anybody ever succesfully implemented Infinite Scroll to the MUI grid system? I'm out of ideas, I can't fall asleep) Somebody help)

Upvotes: 3

Views: 4456

Answers (2)

Ujith Nimantha
Ujith Nimantha

Reputation: 305

I was able to fix this by adding the hasChildren prop to InfiniteScroll. It is in their documentation here. react-infinite-scroll-component

<InfiniteScroll
   dataLength={data.length}
   next={fetchMoreData}
   hasMore={Boolean(nextPage)}
   hasChildren={Boolean(totalCount)} //Add this, 0 items false and 1 or more true
   loader={
     <Box sx={{ my: theme => theme.spacing(6) }}>
       <LoadingSkeletonCard count={totalCount - data.length} />
     </Box>
   }
   endMessage={renderEndMessage(totalCount)}
   >
     <Grid container spacing={6} sx={{ justifyContent: 'center' }}>
       {data.map((item, index) => (
          <Grid item xs={12} md={6} lg={4} key={index}>
            <MyCard item={item} />
          </Grid>
       ))}
     </Grid>
</InfiniteScroll>

Upvotes: 0

meAndrew
meAndrew

Reputation: 309

There's not that much information about InfiniteScroll + MUI grid system, but finally I'm able to make it work. I've left codesanbox sample for you here. Not that beautiful, but it will give an idea how to implement it.

Upvotes: 5

Related Questions