Created
March 12, 2020 15:25
-
-
Save dominictobias/13c774b174e79dc34d655041194c9386 to your computer and use it in GitHub Desktop.
useScrollPos - React hook for scroll position
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 { RefObject, useEffect, useState } from 'react'; | |
export interface ScrollPos { | |
top: number; | |
left: number; | |
} | |
export function useScrollPos(elRef: RefObject<HTMLElement>, disabled?: boolean): ScrollPos { | |
const [scrollPos, setScrollPos] = useState({ top: 0, left: 0 }); | |
useEffect(() => { | |
const el = elRef.current; | |
const onScroll = (e: Event): void => { | |
setScrollPos({ | |
top: (e.target as HTMLDivElement).scrollTop, | |
left: (e.target as HTMLDivElement).scrollLeft, | |
}); | |
}; | |
if (!disabled) { | |
if (el) { | |
el.addEventListener('scroll', onScroll); | |
} | |
} | |
return (): void => { | |
if (el) { | |
el.removeEventListener('scroll', onScroll); | |
} | |
}; | |
}, [elRef, disabled]); | |
return scrollPos; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment