Last active
May 31, 2020 06:49
-
-
Save iksent/f9f6d1627b46c5cb4cb36984b35d8a31 to your computer and use it in GitHub Desktop.
[ReactJS hook] Detect Scrolls To Bottom
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 { useScrollPosition } from '@n8tb1t/use-scroll-position' | |
import { useRef } from 'react' | |
import { get } from 'lodash' | |
export const useOnEndScroll = (onEnd: () => void, disabled: boolean = false) => { | |
const { body, documentElement } = document | |
const isTracking = useRef<boolean>(true) // To avoid repeated requests | |
const offsetFromBottom = 100 | |
useScrollPosition( | |
({ currPos }) => { | |
if (disabled) { | |
return | |
} | |
const scrollHeight = Math.max( | |
get(body, 'scrollHeight'), // get is not necessary, using it to avoid Flow problems | |
get(body, 'offsetHeight'), | |
get(body, 'clientHeight'), | |
get(documentElement, 'scrollHeight'), | |
get(documentElement, 'offsetHeight'), | |
get(documentElement, 'clientHeight'), | |
) | |
const windowHeight = window.innerHeight || get(documentElement, 'offsetHeight') | |
const offset = -currPos.y + windowHeight + offsetFromBottom | |
if (offset >= scrollHeight) { | |
if (isTracking.current) { | |
onEnd() | |
isTracking.current = false | |
} | |
} else if (!isTracking.current) { | |
isTracking.current = true | |
} | |
}, | |
[onEnd, disabled], | |
) | |
} |
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
const PaginatedList = () => { | |
const hasMore = true | |
const request = useCallback(() => { | |
... | |
}, []) | |
useOnEndScroll(request, !hasMore) | |
return ( | |
... | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment