Skip to content

Instantly share code, notes, and snippets.

@scriptex
Created October 25, 2021 11:03
Show Gist options
  • Save scriptex/32ca810d0250aed0e2418226d625d243 to your computer and use it in GitHub Desktop.
Save scriptex/32ca810d0250aed0e2418226d625d243 to your computer and use it in GitHub Desktop.
React hook for smooth scrolling of an element into view
import { useMemo, useLayoutEffect } from 'react';
export const useScrollIntoView = (
selector: string,
options: ScrollIntoViewOptions,
): void => {
const opts: ScrollIntoViewOptions = useMemo(
() => ({
block: 'center',
inline: 'center',
behavior: 'smooth',
...options,
}),
[options],
);
useLayoutEffect(() => {
const element = document.querySelector(selector);
if (element) {
element.scrollIntoView(opts);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment