1

I have a list with a lot of components. When first loads, It shows 20 (index 0 - 19) components and when I scroll it will show more 20 components (index 0 - 39) and so on. Is it possible when I scroll It only show the components ( index 20 - 39 ) and then (index 40 - 59) and so on.

import React, {useState} from 'react';
import InfiniteScroll from "react-infinite-scroll-component";

import './App.css';


const style = {
    height: 30,
    border: "1px solid green",
    margin: 6,
    padding: 8
};



function App() {
  const [items, setItems] = useState( Array.from({length: 20}));

  const fetchMoreData = () => {
      setTimeout(()=> {
          setItems(items.concat(Array.from({length: 20})))
      }, 1500);
  };

  return (
   <div>
       <div>
           <InfiniteScroll
               dataLength={items}
               next={fetchMoreData}
               hasMore={true}
               loader={<h4>Loading...</h4>}
           >
               {items.map((i, index) => (
                   <div style={style} key={index}>
                       div - #{index}
                   </div>
               ))}
           </InfiniteScroll>
       </div>
   </div>
  );
}

export default App;

https://codesandbox.io/s/silly-silence-2rviq?file=/src/App.js:390-436

3
  • What is your question? Commented Apr 13, 2020 at 3:46
  • How when I scroll it just shows 20 components. Commented Apr 13, 2020 at 3:48
  • When I first load it shows 20 components ( 0 - 19) When I scroll it should show 20 components(20 - 39) When I continue it should show 20 components ( 40 - 59) Commented Apr 13, 2020 at 3:58

2 Answers 2

1

You are looking for virtual list.

Take a look at these modules:

react-infinite-scroll-component doesn't have this feature out of the box AFAIK.

Sign up to request clarification or add additional context in comments.

2 Comments

i.sstatic.net/yCxCo.gif Do you know how scroll like this? can I do this with virtual list ?
Virtual list will allow you to render only what's visible. That said, you can use it to create something similar for sure.
0

You are using concat to add new data to your old data, that's why your list is keep adding new data. Just setItems with new array of data, then it will only show 20 current data

const fetchMoreData = () => {
      setTimeout(()=> {
          setItems(new Array(20))
      }, 1500);
  };

Comments

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.