Skip to content

Instantly share code, notes, and snippets.

@sapegin
Created March 12, 2020 12:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sapegin/8637d112abde58552ea0265aef29fe08 to your computer and use it in GitHub Desktop.
Save sapegin/8637d112abde58552ea0265aef29fe08 to your computer and use it in GitHub Desktop.
An accessible React Hook that scrolls to an element
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