Reputation: 65
Here is the my route code:
<Switch>{createRoutes()}</Switch>
const createRoutes = () =>
Routes.map(({ component: Component, urls }) =>
urls.map((url) => (
<Route
path={url}
exact
render={() => <Component/>}
/>
)),
);
const Routes = [
{
urls: ['/'],
component: Home,
},
{
urls: ['/test'],
component: Test,
},
];
And what I want is, when url is '/test?x=1' match component Test, and when url is '/test' will match component Home. How can I be able to do this?
Upvotes: 3
Views: 1691
Reputation: 202751
react-router-dom
only considers the path part of the URL for route matching, there isn't a way to use the queryString to match routes.
What you could do is to create a component that checks the current location
object's search
property and conditionally render the appropriate component.
Example:
const TestWrapper = (props) => {
const { search } = useLocation();
switch (search) {
case "":
return <Home {...props} />;
default:
return <Test {...props} />;
}
};
...
const routes = [
{
paths: ["/"],
component: Home
},
{
paths: ["/test"],
component: TestWrapper
}
];
Additionally, in react-router-dom@5
the Route
component can take an array of paths, so you don't need to explicitly map a route for each path in the paths
array.
const createRoutes = () =>
routes.map(({ component: Component, paths }) => (
<Route key={paths.join()} path={paths} exact component={Component} />
));
Upvotes: 3