React Router: Get All Routes As Array
Solution 1:
As I did not find anything, I ended up creating a library for that...
https://github.com/alansouzati/react-router-to-array
importReactfrom'react';
import { Route, IndexRoute } from'react-router';
import reactRouterToArray from'react-router-to-array';
// or var reactRouterToArray = require('react-router-to-array');console.log(reactRouterToArray(
<Routepath="/"component={FakeComponent}>
{/* just to test comments */}
<IndexRoutecomponent={FakeComponent} /><Routepath="about"component={FakeComponent}><Routepath="home"component={FakeComponent} /><Routepath="/home/:userId"component={FakeComponent} /></Route><Routepath="users"component={FakeComponent} /><Routepath="*"component={FakeComponent} /></Route>)
); //outputs: ['/', '/about', '/about/home', '/users']
Solution 2:
I don't understand why you need a library. Your Routes
should be available as an Array
in the props.
An example:
Solution 3:
I recently released a library specifically for this purpose: https://github.com/elliottsj/react-router-query
It can handle asynchronous routes (i.e. getChildRoutes
/ getIndexRoute
), and provides not just an array of paths, but an array of "FlatRoute" objects which contain the path (fullPath
), plus all of the original properties of each route, and an array of "parent" routes:
import { query } from'react-router-query';
const routes = (
<Routepath="/"component={App}><Routepath="author"component={Author}><Routepath="about"component={About} /></Route><Routepath="users"component={Users} /></Route>
);
query('/', routes, (error, result) => {
expect(result).toEqual([
{
fullPath: '/author/about'component: About,
parents: [
{ path: '/', component: App },
{ path: 'author', component: Author },
],
},
{
fullPath: '/users'component: Users,
parents: [
{ path: '/', component: App },
],
},
]);
});
Note that only "leaf" routes are included in the result: there is no "FlatRoute" object for fullPath: '/'
nor fullPath: '/author'
. This is to prevent including routes that are only used as a layout for child routes, e.g.
<Route path="/" component={App}>
<Routepath="posts"component={PostLayout}><Routepath="1"component={Post1} /><Routepath="2"component={Post2} /><Routepath="3"component={Post3} /></Route>
</Route>
If you want a FlatRoute for /posts
, simply include an IndexRoute
:
<Route path="/" component={App}>
<Routepath="posts"><IndexRoutecomponent={Posts} /><Routepath="1"component={Post1} /><Routepath="2"component={Post2} /><Routepath="3"component={Post3} /></Route>
</Route>
Post a Comment for "React Router: Get All Routes As Array"