Skip to content

Instantly share code, notes, and snippets.

@qWici
Last active December 6, 2021 13:34
Show Gist options
  • Save qWici/70bcf97d697148c323042a0b3395fbed to your computer and use it in GitHub Desktop.
Save qWici/70bcf97d697148c323042a0b3395fbed to your computer and use it in GitHub Desktop.
import { InfiniteScroll } from "@components/infinite-scroll";
import React, { createRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { PageHeader } from "@components/page-header";
import { ContentGrid } from "@components/content-grid";
import { ArticleItem } from "@components/content-items/article";
import { VideoItem } from "@components/content-items/video";
import { PodcastItem } from "@components/content-items/podcast";
import { getFakeItems } from "@/helpers/getFakeItems";
import { ContentItem } from "@/global-types";
import DefaultLayout from "@/layouts/default";
const HomePage: React.FC = () => {
const { t } = useTranslation();
const [items, setItems] = useState<ContentItem[]>(getFakeItems(20));
const scrollParentRef = createRef<HTMLElement>();
const hasMore = true;
const loadMore = (page: number) => {
console.log(page);
const newItems = getFakeItems(20);
setItems([...items, ...newItems]);
};
const renderItems = () => items.map((item, i) => {
switch (item.type) {
case "article":
return (<ArticleItem key={i} {...item} />);
case "video":
return (<VideoItem key={i} {...item} />);
case "podcast":
return (<PodcastItem key={i} {...item} />);
default:
return null;
}
});
return (
<DefaultLayout titleKey="all">
<PageHeader title={t("all")} />
<main className="content-items" ref={scrollParentRef}>
<InfiniteScroll loadMore={loadMore} parentRef={scrollParentRef}>
<ContentGrid>
{ renderItems() }
</ContentGrid>
</InfiniteScroll>
</main>
</DefaultLayout>
);
};
export default HomePage;
import React, {
useCallback, useEffect, useState,
} from "react";
interface InfiniteScrollProps {
parentRef: React.RefObject<HTMLElement>;
loadMore: (page: number) => void;
pageStart?: number;
}
export const InfiniteScroll: React.FC<InfiniteScrollProps> = (props) => {
const {
loadMore, pageStart = 1, parentRef, children,
} = props;
const [page, setPage] = useState<number>(pageStart);
useEffect(() => {
loadMore(page);
}, [page]);
const onScroll = useCallback((e) => {
const parentHeight = e.currentTarget.offsetHeight;
const parentScrollTop = e.currentTarget.scrollTop;
const parentScrollHeight = e.currentTarget.scrollHeight;
if (parentHeight + parentScrollTop === parentScrollHeight) {
setPage((prev) => prev + 1);
}
}, []);
useEffect(() => {
parentRef.current?.addEventListener("scroll", onScroll);
}, [onScroll, parentRef]);
return (
<div>
<>
{ children }
</>
{/* {loading && <p>Loading...</p>} */}
{/* {error && <p>Error!</p>} */}
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment