Skip to content

Instantly share code, notes, and snippets.

@johnnyferreiradev
Created February 15, 2022 13:08
Show Gist options
  • Save johnnyferreiradev/50104922fae3d9b60872aa0770ce119c to your computer and use it in GitHub Desktop.
Save johnnyferreiradev/50104922fae3d9b60872aa0770ce119c to your computer and use it in GitHub Desktop.
Hook that helps to create the infinite scroll effect on a page or element
import { useEffect } from 'react';
const InfiniteScroll = ({ fetchMore, disabled, scrollElement }) => {
const elementScroll = ({ target }) => {
if (!disabled) {
const max = target.scrollHeight - target.clientHeight;
if (target.scrollTop >= max) {
fetchMore();
}
}
};
const pageScroll = () => {
if (!disabled) {
const { offsetHeight, scrollHeight } = document.body;
const scrollTop =
document.body.scrollTop || document.documentElement.scrollTop;
if (offsetHeight + scrollTop >= scrollHeight) {
fetchMore();
}
}
};
useEffect(
() => {
const currentScrollElement = scrollElement || document;
currentScrollElement.addEventListener(
'scroll',
scrollElement ? elementScroll : pageScroll
);
return () => {
currentScrollElement.removeEventListener(
'scroll',
scrollElement ? elementScroll : pageScroll
);
};
},
[disabled, scrollElement]
);
return null;
};
export default InfiniteScroll;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment