40

I'm trying to use React Router in my react app which is bounded as wordpress plugin and uses flux to fetch api data.

my entry point looks as it follows

import React from 'react';
import Workshops  from './components/workshops';
import Workshop  from './components/workshop';
import NotFound  from './components/notfound';
import Router, { Route, DefaultRoute, NotFoundRoute, Redirect, Link } from 'react-router';
import json  from './config.json';
localStorage.clear();
localStorage.setItem('workshops', JSON.stringify(json));

const AppRoutes = (
   <Route path="/" handler={Workshops}>
    <DefaultRoute handler={Workshop} />
    <Route name="workshop" path=":slug" handler={Workshop}/>
    <NotFoundRoute handler={NotFound} />
  </Route>
);

Router.run(AppRoutes, Router.HashLocation, (Root) => {
  React.render(<Root />, document.getElementById('workshop-booker'));
});

than in my Workshops component I make some links to a given route, I have hash changes but the routed component does not getting fired.

<h3> <Link to="workshop" params={{slug: workshop.slug }}> {workshop.title.rendered }</Link></h3>
4
  • What are you looking to debug?
    – Cassidy
    Commented Dec 4, 2015 at 17:23
  • 1
    why the called route does not getting fired, in the example above I would expect on hash change that the worksop component would output on slug a new view
    – fefe
    Commented Dec 4, 2015 at 17:25
  • I want to debug it too, but server side with a ReactRouter.createMemoryHistory(pagePath). B.t.w. in version 1 and 2 it should be component= not handler= — is that your problem perhaps? (& name= is gone) and lots of other stuff has changed too
    – KajMagnus
    Commented Jan 30, 2016 at 21:56
  • I found between a solution -> redux devtools
    – fefe
    Commented Jan 31, 2016 at 15:38

4 Answers 4

51

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

3
  • 1
    That solution may be working but unfortunately for me I no longer have my redirection problem when I encapsulate the Switch component in a BrowserRouter. Edit: my problem was because of a history.push in my code, that method apparently annihilated the history.push command.
    – Jean Paul
    Commented Feb 16, 2021 at 17:22
  • I have recently upgraded to [email protected] (don't know if that's important). But I'm getting an error: react-dom.development.js:14985 Uncaught TypeError: Class constructor DebugRouter cannot be invoked without 'new'
    – Markus
    Commented Sep 12, 2022 at 7:39
  • Oh, I'm guessing it's because I use the function structure instead of class structure.
    – Markus
    Commented Sep 12, 2022 at 8:29
26

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>
  )
}
2
  • 6
    For "react-router-dom": "^6.8.0" I had to change const { location } = useHistory() to const location = useLocation(); where useLocation is imported from "react-router-dom". Commented Feb 11, 2023 at 1:58
  • @JillAndMe could you add all imports to your code snippet, to make it easier to get it to work? Thanks~ Commented Jun 19, 2023 at 8:56
3

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

-4

You can use the following code to debug React Router:

console.log(this.props.location)
console.log(this.props.match)
2
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
    – Nic3500
    Commented Sep 5, 2018 at 0:33
  • 1
    not clear where this should go, I get errors just putting it into the app's render method. addmittedly typescript so it is finding undefined more clearly: Property 'location' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'. TS2339
    – dcsan
    Commented Jul 29, 2019 at 12:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.