prometheus

Форк
0
/
CustomInfiniteScroll.tsx 
50 строк · 1.5 Кб
1
import { ComponentType, useEffect, useState } from 'react';
2
import InfiniteScroll from 'react-infinite-scroll-component';
3

4
const initialNumberOfItemsDisplayed = 50;
5

6
export interface InfiniteScrollItemsProps<T> {
7
  items: T[];
8
}
9

10
interface CustomInfiniteScrollProps<T> {
11
  allItems: T[];
12
  child: ComponentType<InfiniteScrollItemsProps<T>>;
13
}
14

15
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
16
const CustomInfiniteScroll = <T,>({ allItems, child }: CustomInfiniteScrollProps<T>) => {
17
  const [items, setItems] = useState<T[]>(allItems.slice(0, 50));
18
  const [index, setIndex] = useState<number>(initialNumberOfItemsDisplayed);
19
  const [hasMore, setHasMore] = useState<boolean>(allItems.length > initialNumberOfItemsDisplayed);
20
  const Child = child;
21

22
  useEffect(() => {
23
    setItems(allItems.slice(0, initialNumberOfItemsDisplayed));
24
    setHasMore(allItems.length > initialNumberOfItemsDisplayed);
25
  }, [allItems]);
26

27
  const fetchMoreData = () => {
28
    if (items.length === allItems.length) {
29
      setHasMore(false);
30
    } else {
31
      const newIndex = index + initialNumberOfItemsDisplayed;
32
      setIndex(newIndex);
33
      setItems(allItems.slice(0, newIndex));
34
    }
35
  };
36

37
  return (
38
    <InfiniteScroll
39
      next={fetchMoreData}
40
      hasMore={hasMore}
41
      loader={<h4>loading...</h4>}
42
      dataLength={items.length}
43
      height={items.length > 25 ? '75vh' : ''}
44
    >
45
      <Child items={items} />
46
    </InfiniteScroll>
47
  );
48
};
49

50
export default CustomInfiniteScroll;
51

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.