Categories
React Answers

How to get all routes as array with React Router?

Spread the love

Sometimes, we want to get all routes as array with React Router.

In this article, we’ll look at how to get all routes as array with React Router.

How to get all routes as array with React Router?

To get all routes as array with React Router, we can use the react-router-to-array package.

To install it, we run

npm i react-router-to-array

Then we use it by writing

import React from "react";
import { Route, IndexRoute } from "react-router";
import reactRouterToArray from "react-router-to-array";

console.log(
  reactRouterToArray(
    <Route path="/" component={Home}>
      <Route path="about" component={About}>
        <Route path="home" component={Home} />
        <Route path="/home/:userId" component={Home} />
      </Route>
      <Route path="users" component={Users} />
      <Route path="*" component={NotFound} />
    </Route>
  )
);

to call reactRouterToArray with the Route component.

As a result, we should see an array of Route component path values logged.

Conclusion

To get all routes as array with React Router, we can use the react-router-to-array package.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *