Created
October 25, 2021 11:03
-
-
Save scriptex/32ca810d0250aed0e2418226d625d243 to your computer and use it in GitHub Desktop.
React hook for smooth scrolling of an element into view
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 { 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