Multiple path names for a same component in React Router

As of react-router v4.4.0-beta.4, and officially in v5.0.0, you can now specify an array of paths which resolve to a component e.g.

<Router>
    <Route path={["/home", "/users", "/widgets"]} component={Home} />
</Router>

Each path in the array is a regular expression string.

The documentation for this approach can be found here.

Update for React Router v6

React Router v6 no longer allows an array of paths to be passed as a Route property. Instead you can make use of the useRoutes (see here for documentation) React hook to achieve the same behaviour:

import React from "react";
import {
  BrowserRouter as Router,
  useRoutes,
} from "react-router-dom";

const App = () => useRoutes([
    { path: "/home", element: <Home /> },
    { path: "/users", element: <Home /> },
    { path: "/widgets", element: <Home /> }
  ]);

const AppWrapper = () => (
    <Router>
      <App />
    </Router>
  );

You can see an extended example of this code working here.

The key take away from this answer is:

The useRoutes hook is the functional equivalent of <Routes>, but it
uses JavaScript objects instead of <Route> elements to define your
routes.

Leave a Comment

tech