Created
February 16, 2021 21:35
-
-
Save Dexdot/f42c5c0bb1fdaf414160ca110c3a98f4 to your computer and use it in GitHub Desktop.
Scroll on bottom (React<TS>)
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 { useRef, useEffect, useState, useCallback } from 'react'; | |
interface ReturnDataI { | |
ref: React.MutableRefObject<Element | null>; | |
isBottom: boolean; | |
} | |
export function useScrollBottom(offset = 0): ReturnDataI { | |
const ref = useRef<Element>(null); | |
const [isBottom, setIsBottom] = useState<boolean>(false); | |
const onScroll = useCallback(() => { | |
if (ref && ref.current) { | |
setIsBottom( | |
ref.current.getBoundingClientRect().bottom <= | |
window.innerHeight + offset | |
); | |
} | |
}, []); | |
useEffect(() => { | |
document.addEventListener('scroll', onScroll); | |
return () => { | |
document.removeEventListener('scroll', onScroll); | |
}; | |
}, []); | |
return { | |
ref, | |
isBottom | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment