Skip to content

Instantly share code, notes, and snippets.

@iksent
Last active May 31, 2020 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iksent/f9f6d1627b46c5cb4cb36984b35d8a31 to your computer and use it in GitHub Desktop.
Save iksent/f9f6d1627b46c5cb4cb36984b35d8a31 to your computer and use it in GitHub Desktop.
[ReactJS hook] Detect Scrolls To Bottom
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],
)
}
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