Search code examples
javascriptreactjsreact-hooksnext.jsnext-router

how to listen to page changes in nextjs


I want to reuse a menu I made in react with react-router-dom, but this time in nextjs. The goal is to change the state of the menu to 'false' and the menuName to 'menu' when I click on a link inside the menu.

I use a useEffect function to listen history :

//use effect for page changes
  useEffect(() => {
    //listen for page changes
    history.listen(() => {
      setState({ clicked: false, menuName: "Menu" })
    })
  })

and wrapped my component with withRouter :

import { withRouter } from 'next/router'
[...]
export default withRouter(Header);

Unfortunately, it prints :

TypeError: Cannot read property 'listen' of undefined

Should I better use 'useRouter' to solve this problem? How?

Thank you ;)


Solution

  • It worked that way :

    Nextjs : Router Events

    import { useRouter } from "next/router";
    
    ...
    
    const router = useRouter()
      useEffect(() => {
        const handleRouteChange = (url) => {
          console.log(
            `App is changing to ${url}`
          )
          setState({ clicked: false, menuName: "Menu" })
        }
    
        router.events.on('routeChangeStart', handleRouteChange)
    
        // If the component is unmounted, unsubscribe
        // from the event with the `off` method:
        return () => {
          router.events.off('routeChangeStart', handleRouteChange)
        }
      }, [])