Skip to content

Instantly share code, notes, and snippets.

@ChaseH88
Created March 6, 2023 02:52
Show Gist options
  • Save ChaseH88/09fe957abb18f404e72674a82ab63bc8 to your computer and use it in GitHub Desktop.
Save ChaseH88/09fe957abb18f404e72674a82ab63bc8 to your computer and use it in GitHub Desktop.
This hook uses useLayoutEffect to scroll to an element with a specific ID extracted from the URL, but only after the content has finished loading.
const useScrollToElementOnMount = (loading: boolean) => {
useLayoutEffect(() => {
const isDirectLink = !document.referrer
const hash = window.location.hash
if (isDirectLink && hash) {
const elementId = hash.substring(1)
const element = document.getElementById(elementId)
if (element && !loading) {
element.scrollIntoView({ behavior: 'smooth' })
}
}
}, [loading])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment