Skip to content

Instantly share code, notes, and snippets.

@moshemal
Last active November 9, 2023 00:26
Show Gist options
  • Save moshemal/540ccb312b3d9941463789eff3c565a4 to your computer and use it in GitHub Desktop.
Save moshemal/540ccb312b3d9941463789eff3c565a4 to your computer and use it in GitHub Desktop.
Debug react-router routings
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Login from 'components/Login'
import DefaultComponent from 'components/DefaultComponent'
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));
});
}
}
class App extends Component {
render() {
return (
<DebugRouter>
<Switch>
<Route exact path="/login" name="Login Page" component={Login} />
<Route path="/" name="Home" component={DefaultComponent} />
</Switch>
</DebugRouter>
);
}
}
@wonsuc
Copy link

wonsuc commented Feb 18, 2021

Here is the hacky way to use this with a Typescirpt based project.

  1. Create DebugRouter.jsx file.
  2. Copy & Paste these codes.
import {BrowserRouter} from "react-router-dom";

// noinspection JSUnresolvedVariable
export class DebugRouter extends BrowserRouter {
    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));
        });
    }
}
  • Basically you have to ignore ts-lint error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment