How to debug React Router? How to debug React Router? reactjs reactjs

How to debug React Router?


You can wrap your Router with a DebugRouter which will print the navigation actions made:

import React, { Component } from 'react';import { BrowserRouter, Route, Switch } from 'react-router-dom';import Login from 'components/Login'import DefaultComponent from 'components/DefaultComponent'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));    });  }}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>    );  }}

link to the gist


I made my DebugRouter for functional components

const DebugRouter = ({ children }: { children: any }) => {  const { location } = useHistory()  if (process.env.NODE_ENV === 'development') {    console.log(      `Route: ${location.pathname}${location.search}, State: ${JSON.stringify(location.state)}`,    )  }  return children}const Router = () => {  return (    <BrowserRouter>      <Layout>        <Route          render={() => {            return (              <DebugRouter>                <Switch>                  <Redirect exact from="/" to={...} />                  // <Route/> should be here                  <Redirect from="*" to={...} />                </Switch>              </DebugRouter>            )          }}        />      </Layout>    </BrowserRouter>  )}


You can try something like this

import React, {Component} from 'react';import PropTypes from 'prop-types'import {withRouter} from "react-router-dom";class RouterDebugger extends Component {    componentWillUpdate(nextProps, nextState){        console.log('componentWillUpdate',nextProps, nextState)    }    componentDidUpdate(prevProps) {        console.log('componentDidUpdate',prevProps)    }    render() {        return null    }}export default withRouter(RouterDebugger)

And insert this component in any place you want to debug.You can pass a prop with some identifier i hope this help you