Cant fire scroll event on react

I have a submenu element, which appears when the user hovers over a menu item, and hides when(well you can guess when). I want to make it hide when the user scrolls the page.

useEffect(()=>{
  //window.onscroll=()=>this does work/
  const handleScroll=()=>{
    console.log('scroooolling...')
    setSubmenu(false)
  }
  window.addEventListener('scroll', handleScroll)
  return window.removeEventListener('scroll', handleScroll)
}, []) 

I have added this hook in the submenu element, but the event listener does not fire. window.onscroll works, but it does not fit my needs.
Is there any general reason why react would not register the scroll event?

Is there a reason you wouldn’t use the React onScroll property?

const App = () => (
  <div
    style={ {
      border: '1px solid black',
      width: '200px',
      height: '300px',
      overflow: 'scroll',
    } }
    onScroll={ handleScroll }
  >
    { /* whatever */ }
  </div>
)

Here is a working pen .

Don’t you just need to return a function instead?

return () => window.removeEventListener("scroll", handleScroll);
1 Like

yes i always mess up that part, ill fix it and see if it still doesnt work

@kevinSmith the functionality is such that i want to register if the user is scrolling the whole page, not just certain element. I did check however if attaching listener to the “root” element should work, but it did not.
The whole problem came when i placed the submenu to be position fixed, so when i scroll, it doesnt float with the document. Position absolute had another positioning issues involved, so i did not use that

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.