Enea Xharja Logo

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';
2
3const useScrollToHash = hash => {
4 useEffect(() => {
5 if (!hash) return;
6
7 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};
14
15export default useScrollToHash;
© 2021 Enea Xharja