react-router: debugging the router

2021-09-24

 | 

~1 min read

 | 

169 words

A situation came up recently where I was getting very peculiar results with my router.1

To help understand what was going on, I looked into how to debug a react router.

My favorite answer was a functional component that I could use to wrap my Router.

In practice it looked a bit like this:

export const App = () => {
  return (
    <Router basename="/menu-management">
      <DebugRouter>
        <Switch>
          <Route path="/subpage">
            <SubPage />
          </Route>
          <Route path="/">
            <Main />
          </Route>
        </Switch>
      </DebugRouter>
    </Router>
  )
}

The actual component is easy to reason through:

const DebugRouter = ({ children }: React.PropsWithChildren<unknown>) => {
  const { location } = useHistory()
  if (process.env.NODE_ENV === "development") {
    console.log(
      `Route: ${location.pathname}${location.search}, State: ${JSON.stringify(
        location.state,
      )}`,
    )
  }

  return children
}

When the component renders, we’ll track the state of our router.

Footnotes



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!