function Table() {
// Dummy example
const [page, setPage] = useState(0);
const pages = 5;
const hasMore = page < pages;
function loadMore() {
setPage(previousPage => previousPage + 1);
}
const loadMoreRef = useLoadMoreTarget(loadMore);
return (
<>
<AllMyTableRows />
{hasMore && <div ref={loadMoreRef} />}
</>
)
}
Last active
February 24, 2022 12:59
-
-
Save simenbrekken-visma/11d619f0707f6ee2ab4b8ca6163c861c to your computer and use it in GitHub Desktop.
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 { useEffect, useRef } from 'react'; | |
export function useLoadMoreTarget<T extends HTMLElement>( | |
loadMore: () => void, | |
{ root, rootMargin, threshold }: IntersectionObserverInit = {} | |
): React.MutableRefObject<T | null> { | |
const targetRef = useRef<T | null>(null); | |
const loadMoreRef = useRef(loadMore); | |
useEffect(() => { | |
loadMoreRef.current = loadMore; | |
}, [loadMore]); | |
useEffect(() => { | |
const target = targetRef.current; | |
const loadMore = loadMoreRef.current; | |
if (target === null) { | |
return; | |
} | |
function onIntersection(entries: IntersectionObserverEntry[]) { | |
if (entries[0].isIntersecting) { | |
loadMore(); | |
} | |
} | |
const observer = new IntersectionObserver(onIntersection, { | |
root, | |
rootMargin, | |
threshold, | |
}); | |
observer.observe(target); | |
return () => { | |
observer.unobserve(target); | |
}; | |
}, [root, rootMargin, threshold]); | |
return targetRef; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment