How to get all routes as array with React Router?

Sometimes, we want to get all routes as array with React Router.

In this article, we’ll look at how to get all routes as array with React Router.

How to get all routes as array with React Router?

To get all routes as array with React Router, we can use the react-router-to-array package.

To install it, we run

npm i react-router-to-array

Then we use it by writing

import React from "react";
import { Route, IndexRoute } from "react-router";
import reactRouterToArray from "react-router-to-array";

console.log(
  reactRouterToArray(
    <Route path="/" component={Home}>
      <Route path="about" component={About}>
        <Route path="home" component={Home} />
        <Route path="/home/:userId" component={Home} />
      </Route>
      <Route path="users" component={Users} />
      <Route path="*" component={NotFound} />
    </Route>
  )
);

to call reactRouterToArray with the Route component.

As a result, we should see an array of Route component path values logged.

Conclusion

To get all routes as array with React Router, we can use the react-router-to-array package.