Last active
March 24, 2023 03:22
-
-
Save tlux/b35cc6800809e5c83d6b0e2be2e1beba to your computer and use it in GitHub Desktop.
React hook to track and set scroll position of an element
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 { 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