hyperlinkreactjsreact-router

How to debug React Router?


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>

Solution

  • 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