Search code examples
reactjsnext.jsnext-router

How to listen to changes in router and force to a class component to re-render?


Working with the framework Next.js and a class component, I'm trying to get the actual query in order to update the DOM. I'm getting the router using next/router but it return the previous one, not the actual url. Here is an example:

When the user visit for the first time the page which contains the form, this will apear:

  • route: /signup?option=signup
  • form rendered: login

If the user clicks on a Link next/Link that points to /signup?option=login, this will apear:

  • route: /signup?option=login
  • form rendered: login

So, taking this as example, I would like to know how to listen to router and force the virtual DOM to rnder again if this has changed.

Here is how I'm getting the router and passing it to the class component:

import { withRouter } from 'next/router'

class Register extends Component {
    constructor({router, ...props}) {
        super(props);
        this.state = {  
            completed: false,
            signup: router.query.option=='signup'? true: false, //This works the very first time
   }
   }
   ...
  }
export default withRouter(Register);

Thank you in advance for your time and answers!


Solution

  • You are using next/router

    it provides an event routeChangeComplete which will fire when routes change.

    This should help

    https://nextjs.org/docs/api-reference/next/router#userouter

    here is example code how you might use it.

    componentDidMount(){
            router.events.on('routeChangeComplete', (url, {shallow})=>{
                console.log(url, shallow);
                // compare your state and new hash url here and update the state based
                // on requirements
            });
        }