Alan Souza Alan Souza - 3 months ago 67
React JSX Question

React Router: get all routes as array

Is there an existing library that will reduce my route instance to an array of paths?

Example:

<Route path="/" component={App}>
<Route path="author" component={Author}>
<Route path="about" component={About}/>
</Route>
<Route path="users" component={Users} />
</Route>


Output

['/', '/author', '/author/about', '/users']


I could write a reduce function that will have few lines of code and solve that, but I was wondering if there is an existing library that will do that for me and take care of the different ways of representating routes using react router.

Answer

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']
Comments