Created
March 12, 2020 12:36
-
-
Save sapegin/8637d112abde58552ea0265aef29fe08 to your computer and use it in GitHub Desktop.
An accessible React Hook that scrolls to an element
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 { useCallback, useRef, RefObject } from 'react'; | |
/** | |
* Scroll to an element. | |
*/ | |
export default function useScroll<T extends HTMLElement>( | |
options: Omit<ScrollIntoViewOptions, 'behavior'> = {}, | |
): [RefObject<T>, () => void] { | |
const ref = useRef<T>(null); | |
const callback = useCallback(() => { | |
if (ref.current) { | |
// Don't use smooth scrolling when the user prefers reduced motion | |
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)'); | |
ref.current.scrollIntoView({ | |
...options, | |
behavior: prefersReducedMotion ? undefined : 'smooth', | |
}); | |
} | |
}, []); | |
return [ref, callback]; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment