Scroll to Hash in Gatsby
The useScrollToHash
hook uses the location
prop from a Gatsby page to scroll to a specific element on the page. Then, it adds a hash to the URL.
js
1import { useEffect } from 'react';23const useScrollToHash = hash => {4 useEffect(() => {5 if (!hash) return;67 window.requestAnimationFrame(() => {8 const anchor = document.querySelector(hash);9 const offset = anchor.getBoundingClientRect().top + window.scrollY;10 window.scroll({ top: offset, left: 0 });11 });12 }, []);13};1415export default useScrollToHash;