github.com/thanos-io/thanos@v0.32.5/pkg/ui/react-app/src/components/CustomInfiniteScroll.tsx (about)

     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  const CustomInfiniteScroll = <T,>({ allItems, child }: CustomInfiniteScrollProps<T>) => {
    16    const [items, setItems] = useState<T[]>(allItems.slice(0, 50));
    17    const [index, setIndex] = useState<number>(initialNumberOfItemsDisplayed);
    18    const [hasMore, setHasMore] = useState<boolean>(allItems.length > initialNumberOfItemsDisplayed);
    19    const Child = child;
    20  
    21    useEffect(() => {
    22      setItems(allItems.slice(0, initialNumberOfItemsDisplayed));
    23      setHasMore(allItems.length > initialNumberOfItemsDisplayed);
    24    }, [allItems]);
    25  
    26    const fetchMoreData = () => {
    27      if (items.length === allItems.length) {
    28        setHasMore(false);
    29      } else {
    30        const newIndex = index + initialNumberOfItemsDisplayed;
    31        setIndex(newIndex);
    32        setItems(allItems.slice(0, newIndex));
    33      }
    34    };
    35  
    36    return (
    37      <InfiniteScroll
    38        next={fetchMoreData}
    39        hasMore={hasMore}
    40        loader={<h4>loading...</h4>}
    41        dataLength={items.length}
    42        height={items.length > 25 ? '75vh' : ''}
    43      >
    44        <Child items={items} />
    45      </InfiniteScroll>
    46    );
    47  };
    48  
    49  export default CustomInfiniteScroll;