Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 394
Alan Souza Avatar asked Jun 13 '16 22:06

Alan Souza


2 Answers

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']
like image 88
Alan Souza Avatar answered Nov 12 '22 01:11

Alan Souza


I don't understand why you need a library. Your Routes should be available as an Array in the props.

An example:

enter image description here

like image 7
U r s u s Avatar answered Nov 12 '22 02:11

U r s u s