Ryan Prentiss
Ryan Prentiss

Reputation: 1642

Add Scroll EventListener to Document in GatsbyJS (ReactJS)

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 (
        <>...</>
    )
}

Upvotes: 5

Views: 2041

Answers (1)

Ryan Prentiss
Ryan Prentiss

Reputation: 1642

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 (
        <>...</>
    )
}

Upvotes: 4

Related Questions