Add Scroll EventListener to Document in GatsbyJS (ReactJS)

Viewed 1640

How should I add the following eventlistener to a GatsbyJS (ReactJS) functional component?

EventListener

document.addEventListener('scroll', _ => document.getElementById('logo').style.setProperty('--v-adjust', window.scrollY + 'px'))

Functional Component

import React from 'react'
import { Link, useStaticQuery, graphql } from 'gatsby'

export default () => {
    //graphql statement
    return (
        <>...</>
    )
}
1 Answers

I needed the useEffect hook to perform the action. Using the Effect Hook

Updated Component

import React, { useEffect } from 'react'

export default () => {
    useEffect(() => {
        document.addEventListener('scroll', _ => document.getElementById('logo').style.setProperty('--v-adjust', window.scrollY + 'px'))
    })
    return (
        <>...</>
    )
}
Related