Skip to content

Instantly share code, notes, and snippets.

@tlux
Last active March 24, 2023 03:22
Show Gist options
  • Save tlux/b35cc6800809e5c83d6b0e2be2e1beba to your computer and use it in GitHub Desktop.
Save tlux/b35cc6800809e5c83d6b0e2be2e1beba to your computer and use it in GitHub Desktop.
React hook to track and set scroll position of an element
import { RefObject, useCallback, useEffect, useState } from 'react';
export interface ScrollToOptions {
x?: number;
y?: number;
behavior?: ScrollBehavior;
}
export interface UseScrollOptions {
disabled?: boolean;
}
export default function useScroll<T extends Element>(
ref: RefObject<T>,
{ disabled = false }: UseScrollOptions = {}
) {
const [position, setPosition] = useState({ x: 0, y: 0 });
useEffect(() => {
const el = ref.current;
if (!el || disabled) return;
function updatePosition() {
setPosition({
x: el?.scrollLeft ?? 0,
y: el?.scrollTop ?? 0,
});
}
updatePosition();
el.addEventListener('scroll', updatePosition);
return () => {
el.removeEventListener('scroll', updatePosition);
};
}, [disabled, ref]);
const scrollTo = useCallback(
({ x, y, behavior }: ScrollToOptions) => {
ref.current?.scrollTo({ left: x, top: y, behavior });
},
[ref]
);
return [position, scrollTo] as const;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment