Sometimes, we want to match multiple path names for a same component in React Router
In this article, we’ll look at how to match multiple path names for a same component in React Router.
How to match multiple path names for a same component in React Router?
To match multiple path names for a same component in React Router, we can make changes according to the React Route version we’re using.
If we’re using React Router v4, we set the path
prop to an array of paths to match.
For instance, we write
<Router>
<Route path={["/home", "/users", "/widgets"]} component={Home} />
</Router>
to set the path
prop to ["/home", "/users", "/widgets"]
to match all of the routes listed.
In React Router v6, we use the useRoutes
hook by writing
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>
);
We call useRoutes
with an array of route objects and then wrap Router
around that to add the routes to our app.
path
has the path and element
has the component to render given the path
.
Conclusion
To match multiple path names for a same component in React Router, we can make changes according to the React Route version we’re using.