Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
useScrollPos - React hook for scroll position
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