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>
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.
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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With