Last active
November 9, 2019 01:51
-
-
Save oukayuka/2cf8e7c2a1603bdd73ce2cb4c634b0f2 to your computer and use it in GitHub Desktop.
Infinit scroll component sample with React Hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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