Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple path names for a same component in React Router

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>
like image 313
Chetan Garg Avatar asked Oct 09 '22 02:10

Chetan Garg


People also ask

Does react router allows for nested routes?

Nested Routes are a powerful feature. While most people think React Router only routes a user from page to page, it also allows one to exchange specific fragments of the view based on the current route.

How are routes defined in react router?

React Router is used to define multiple routes in the application. When a user types a specific URL into the browser, and if this URL path matches any 'route' inside the router file, the user will be redirected to that particular route.

How do I change the default path in react router?

Use the Navigate element to set a default route with redirect in React Router, e.g. <Route path="/" element={<Navigate to="/dashboard" />} /> . The Navigate element changes the current location when it is rendered. Copied!


1 Answers

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.

like image 288
Ben Smith Avatar answered Oct 19 '22 19:10

Ben Smith