Snippet

Scroll to Hash for Gatsby

js
import { useEffect } from 'react'useEffect(() => {    const { hash } = location    if (!hash) return    window.requestAnimationFrame(() => {        const anchor = document.querySelector(hash)        const offset = anchor.getBoundingClientRect().top + window.scrollY        window.scroll({ top: offset, left: 0 })    })}, [])

Context

It is commonly known you can scroll a website on load to a specific element by appending the id of said element after a hash to a url. However, if the content is not present when the page finishes load, the browser will not be able to do the scrolling automatically. This snippet takes care of scrolling to the selected element (if any) once content has loaded.

Keep in mind you'll need to accept the location prop from your Gatsby page to get the hash.

Enjoyed the article? Consider sharing it on Twitter so others can enjoy it too :)

Receive project updates, article drafts & thoughts on your inbox every saturday.

Subscribe