Is there an existing library that will reduce my route instance to an array of paths?
Example:
As I did not find anything, I ended up creating a library for that...
https://github.com/alansouzati/react-router-to-array
import React from '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(
<Route path="/" component={FakeComponent}>
{/* just to test comments */}
<IndexRoute component={FakeComponent} />
<Route path="about" component={FakeComponent}>
<Route path="home" component={FakeComponent} />
<Route path="/home/:userId" component={FakeComponent} />
</Route>
<Route path="users" component={FakeComponent} />
<Route path="*" component={FakeComponent} />
</Route>)
); //outputs: ['/', '/about', '/about/home', '/users']
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 = (
<Route path="/" component={App}>
<Route path="author" component={Author}>
<Route path="about" component={About} />
</Route>
<Route path="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}>
<Route path="posts" component={PostLayout}>
<Route path="1" component={Post1} />
<Route path="2" component={Post2} />
<Route path="3" component={Post3} />
</Route>
</Route>
If you want a FlatRoute for /posts
, simply include an IndexRoute
:
<Route path="/" component={App}>
<Route path="posts">
<IndexRoute component={Posts} />
<Route path="1" component={Post1} />
<Route path="2" component={Post2} />
<Route path="3" component={Post3} />
</Route>
</Route>
I don't understand why you need a library. Your Routes
should be available as an Array
in the props.
An example: