fisshy / react-scroll

React scroll component
https://github.com/fisshy/react-scroll/blob/master/README.md
MIT License
4.36k stars 437 forks source link

scrollEvent on end not triggered at all (Scroll Spy and Update react-router url) #545

Open mnlbox opened 1 year ago

mnlbox commented 1 year ago

Hi,

I'm trying to implement scrollSpy to update react-router URL based on the viewing section with hashlink, this is my code:

import { useLocation } from 'react-router-dom'
import { Link as ScrollLink, scroller, Events, scrollSpy } from 'react-scroll'

...
export default function App() {
 const { hash } = useLocation()
  const handleScroll = (to: string, element: string) => {
    console.log('scroll')
    console.log(to)
    console.log(element)
    const currentSection = scroller.getActiveLink()
    const currentHash = `#${currentSection}`
    console.log('currentHash:', currentHash)
    console.log('hash:', hash)
    if (hash !== currentHash) {
      window.history.replaceState(null, '', currentHash)
      scrollSpy.update()
    }
  }
  useEffect(() => {
    console.log('hash:', hash)
    console.log(Events)
    Events.scrollEvent.register('end', handleScroll)
    return () => {
      Events.scrollEvent.remove('end')
    }
  }, [hash])

As I checked the handleScroll not calling at all when I scrolling the page. As I printed console.log(Events) it seems the event is registered successfully but noting triggered when I scroll. I don't have any idea how to debug or fix this. Any idea?