Graphics Cove

How to Debug React Router

Have you been stuck trying to understand why your React Router doesn't do what you want it to?

An easy way to debug React Router is to extend the default Router class and print the navigation actions made to the developer console.

Debug Class

The below class extended the default Router class, allowing you to log various actions while you navigate the site.

class DebugRouter extends Router {
        constructor(props){
            super(props);
            console.log('initial history is: ', JSON.stringify(this.history, null,2))
            this.history.listen((location, action)=>{
                console.log(
                    `The current URL is ${location.pathname}${location.search}${location.hash}`
                )
                console.log(`The last navigation action was ${action}`, JSON.stringify(this.history, null,2));
            });
        }
    }

This should give you enough detail to understand what's happening under the hood, and guide you in the direction of where the issue lies.

© 2010 - 2023 Graphicscove

TwitterFacebookFAQsPrivacy PolicyFree Website Review