0

I'm trying to make a 'scroll-up' button to appear and disappear depending on a scrolled position. So I'm trying to grab the scrolled position value dynamically but I am only able to grab the data once upon load, I want to grab it everytime i scroll.

I kind of know how to make it work with react-hooks with useEffect however the project is built using class components.

My approach to this was using componentDidMount like so:

componentDidMount() {
    console.log('mount success')
    console.log('pageYOffset', window.pageYOffset)
    window.addEventListener('scroll', this.scrollHandler)
}


scrollHandler = () => {
    const position = window.pageYOffset;
    console.log('Current Scrolled', position)
}

The result in the console is always '0' since it loads first, and then as i scroll i dont get new feedback in the console.

Thanks in advance!

KvnG.
  • 658
  • 1
  • 7
  • 17
  • are you sure that you scroll window? or it some nested scroll? – Oro Jan 06 '22 at 08:35
  • did you try to add some HTML tag with onScroll prop? https://www.w3schools.com/tags/ev_onscroll.asp – Ar26 Jan 06 '22 at 08:39
  • 1
    @RamanNikitsenka thank you, this question helped me narrow the issue. The 'window' was not supposed to be the target, should be a div instead and the position was displaying as expected. – KvnG. Jan 08 '22 at 06:47
  • will be great if you vote some of my other answers in other questions (see them in my profile) I will be thankful – Oro Jan 08 '22 at 15:13

1 Answers1

1
<div onScroll={() => console.log(window.pageYOffset)}>>
</div>

or with a event listener

componentDidMount() {
window.addEventListener('scroll', function(e) {
            console.log(window.pageYOffset)
        })
}

componentWillUnmount() {
window.removeEventListener('scroll', function(e) {
            console.log(window.pageYOffset)
        })
}

Aakash Rathee
  • 523
  • 3
  • 17