3

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?

1 Answer 1

3

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} />
  ));

Edit how-can-i-differentiate-query-parameters-in-routing-paths-in-react-router

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.