Gatsby window scroll position

Gatsby will fail to build if you refer to window, so we need a work around.

Place this inside the component and you’ll have access to the scroll state.

import React, { useEffect, useState } from "react"

[...]

const [offset, setOffset] = useState(0)

useEffect(() => {
  if (typeof window !== `undefined`) {
    window.onscroll = () => {
      setOffset(window.pageYOffset)
    }
  }
}, [])

console.log(offset)

[...]Code language: JavaScript (javascript)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.