Alan Souza Alan Souza - 1 month ago 32x
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?


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


['/', '/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.


As I did not find anything, I ended up creating a library for that...

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');

  <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 path="users" component={FakeComponent} />
    <Route path="*" component={FakeComponent} />
); //outputs: ['/', '/about', '/about/home', '/users']