Created
February 15, 2022 13:08
-
-
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
This file contains hidden or 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 } 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