Multiple path names for a same component in React Router

JavascriptReactjsPathReact RouterUrl Routing

Javascript Problem Overview


I am using the same component for three different routes:

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

Is there anyway to combine it, to be like:

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

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

At least with react-router v4 the path can be a regular expression string, so you can do something like this:

<Router>
    <Route path="/(home|users|widgets)/" component={Home} />
</Router>

As you can see it's a bit verbose so if your component/route is simple like this it's probably not worth it.

And of course if this actually comes up often you could always create a wrapping component that takes in an array paths parameter, which does the regex or .map logic reusably.

Solution 3 - Javascript

I don't think it is if you use a version of React Router lower than v4.

You can use a map as you would do with any other JSX component though:

<Router>
    {["/home", "/users", "/widgets"].map((path, index) => 
        <Route path={path} component={Home} key={index} />
    )}
</Router>

EDIT

You can also use a regex for the path in react-router v4 as long as it's supported by path-to-regexp. See @Cameron's answer for more info.

Solution 4 - Javascript

As of react-route-dom v5.1.2 you can pass multiple path as below

 <Route path={"/home" | "/users" | "/widgets"} component={Home} />

And obvoiusly you need to import Home jsx file on top.

Solution 5 - Javascript

As of react router v6 they removed the option for regex and according to the type definition it is again path: string. Currently you would have to spell each path out again or use a map for convenience:

<Routes>
    {('home', 'users', 'widgets').map(path => <Route path={path} element={<Home />} />)}
</Routes>

See also https://reactrouter.com/docs/en/v6/upgrading/v5#note-on-route-path-patterns

Solution 6 - Javascript

Other option: use route prefix. /pages for example. You will get

  • /pages/home
  • /pages/users
  • /pages/widgets

And then resolve it in a detailed way inside the Home component.

<Router>
  <Route path="/pages/" component={Home} />
</Router>

Solution 7 - Javascript

As per React Router docs the proptype 'path' is of type string .So there is no way you could pass an array as props to the Route Component.

If your intention is to only change route you can use the same component for different route no issues with that

Solution 8 - Javascript

With react-router v6, you can do like this:

<Routes>
  {['path1', 'path2'].map((path) => (
            <Route path={path} element={<SomeComponent />} />
  ))}
</Routes>

react-router docs says:

> React Router v6 uses a simplified path format. <Route path> in v6 supports only 2 kinds of placeholders: dynamic :id-style params and * wildcards.

https://reactrouter.com/docs/en/v6/upgrading/v5#note-on-route-path-patterns

Solution 9 - Javascript

here is a little function to transform your custom routes with a paths prop to multiple standard routes supported by react-router v6, with path prop:

const normalizeRoutes = (routes) =>
  routes.reduce((acc, curr) => {
    const newRoute = curr.children
      ? { ...curr, children: normalizeRoutes(curr.children) }
      : curr;
    if (newRoute.paths) {
      return [
        ...acc,
        ...newRoute.paths.map((path) => {
          const { paths, ...rest } = newRoute;
          return { ...rest, path };
        })
      ];
    }
    return [...acc, newRoute];
  }, []);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChetan GargView Question on Stackoverflow
Solution 1 - JavascriptBen SmithView Answer on Stackoverflow
Solution 2 - JavascriptCameronView Answer on Stackoverflow
Solution 3 - JavascriptChristopher ChicheView Answer on Stackoverflow
Solution 4 - JavascriptAbhishekView Answer on Stackoverflow
Solution 5 - JavascriptbasView Answer on Stackoverflow
Solution 6 - JavascriptarturtrView Answer on Stackoverflow
Solution 7 - JavascriptVijaykrish93View Answer on Stackoverflow
Solution 8 - JavascriptSandroMarquesView Answer on Stackoverflow
Solution 9 - JavascriptLIITView Answer on Stackoverflow