Skip to content

Instantly share code, notes, and snippets.

@oukayuka
Last active November 9, 2019 01:51
Show Gist options
  • Save oukayuka/2cf8e7c2a1603bdd73ce2cb4c634b0f2 to your computer and use it in GitHub Desktop.
Save oukayuka/2cf8e7c2a1603bdd73ce2cb4c634b0f2 to your computer and use it in GitHub Desktop.
Infinit scroll component sample with React Hooks
import React, { FC, useEffect, useRef } from 'react';
import ListLoader from '../atoms/ListLoader';
type InfinitScrollProps = {
loadMore?: () => void;
hasMore?: boolean;
isLoading?: boolean;
threshold?: number;
};
const InfinitScroll: FC<InifinitScrollProps> = ({
loadMore = () => {},
hasMore = false,
isLoading = false,
threshold = 150,
children,
}) => {
const ref = useRef() as React.MutableRefObject<HTMLDivElement>;
const handleScroll = () => {
if (!ref.current || !hasMore || isLoading) return;
const { clientHeight } = ref.current;
if (
window.innerHeight + document.documentElement.scrollTop + threshold >
clientHeight
) {
loadMore();
}
};
useEffect(() => {
window.addEventListener('scroll', handleScroll, true);
return () => {
window.removeEventListener('scroll', handleScroll);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<div ref={ref} role="feed" aria-busy={isLoading}>
{children}
{isLoading && <ListLoader />}
</div>
);
};
export default InfinitScroll;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment