react: ES6 onScroll never fires

I’ve been trying this out and I can’t seem to get it working.

export default class MyPage extends React.Component {
    render () { 
       return <div className='page-wrapper'
          onWheel={(e)=>console.log('WHEEL!!',e)}
          onScroll={(e)=>console.log('SCROLL!!',e)}>
          {... my page content ...}
        </div>;
    }
}

the onWheel fires normally, but the onScroll is not firing. I dunno if I’m missing something or this is a bug.

Thanks!

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 6
  • Comments: 20 (3 by maintainers)

Most upvoted comments

@ddaza Add a true to the end of that window listener to enable capture mode.

@admiral96 there are problems with the code you posted, but this a bug tracker not a Q&A - you’ll find better help on StackOverflow or something similar.

I meant the former. If that doesn’t work, it’s hard for me to imagine how it could be a React problem.

elem.addEventListener('scroll', this.fireOnScroll , true);

Add a true to the end of that window listener to enable capture mode is working. Thanks @probablyup

If you’re trying to catch scrolls of the whole page, you need to attach a scroll event handler to window by hand. See also #285.

@admiral96 you can check my implementation of onScroll in my module, it is working. https://github.com/cht8687/react-listview-sticky-header/blob/master/src/ReactListView.js#L66-L69

I ran into this myself. It’s not a React problem per se, but more understanding which element is responsible for scrolling. Like @sophiebits mentioned prior, if you want to listen to the window as supposed to a React component, you most likely need to manage an event listener yourself.

Here’s what I did, I hope it will help others:

// We need to listen to scroll events on the window so we
// manage an event listener ourselves.
React.useEffect(() => {
  const handleScroll = e => {
    // Do something here ...
  }
  document.addEventListener("scroll", handleScroll, { passive: true })
  return () => {
    // This cleans up the event handler when the component unmounts.
    document.removeEventListener("scroll", handleScroll)
  }
}, [])

More info on the third argument to addEventListener here https://developers.google.com/web/tools/lighthouse/audits/passive-event-listeners

be live