Created
March 6, 2023 02:52
-
-
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.
This file contains 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
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