Enea Xharja

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.

import { useEffect } from 'react';

const useScrollToHash = (hash) => {
  useEffect(() => {
    if (!hash) return;

    window.requestAnimationFrame(() => {
      const anchor = document.querySelector(hash);
      const offset = anchor.getBoundingClientRect().top + window.scrollY;
      window.scroll({ top: offset, left: 0 });
    });
  }, []);
};

export default useScrollToHash;

Updated on August 01, 2020

Tagged with: gatsby, snippets


Profile picture

Hey there! I'm Enea, a web developer currently working at eqolot. Welcome to my little corner of the web, where I share my personal collection of notes, code snippets, and resources on topics that interest me.

© 2021 Enea Xharja