Frosty619
Frosty619

Reputation: 1489

Add optional query parameters to a dynamic path using React Router

I'm trying to add an optional query parameter to the end of a path, so the URL would look like this: "/user/1/cars?makeYear=2020" or "/user/1/cars". The relevant Route is defined as follows. I'm unable to find guidance on how to add an optional query parameter to an existing path. For example, the following doesn't work:

<Route path="user" element={<UserScreen />}>
  <Route path=":id/makeYear?" element={<User/>} />
</Route>

Here I'd think that <Route path=":id/makeYear?" element={<User/>} /> will mark makeYear as an optional parameter, but no, doesn't work.

I then thought that I'd access the query parameters directly in the component, so given that the URL is "/user/1/cars?makeYear=2020", I can fetch the URL via the useLocation api provided by react-router-dom. However, the query parameter, this doesn't work either as the query parameter is immediately removed from the URL (I'm guessing by react-router).

I'm using react-router-dom (6.2.2).

Upvotes: 3

Views: 23138

Answers (1)

Drew Reese
Drew Reese

Reputation: 202836

react-router-dom doesn't use the queryString for route path matching. Remove the queryString part from the route path prop. Access the query params in the component via the useSearchParams hook.

<Route path=":id" element={<User/>} />

...

import { useSearchParams } from 'react-router-dom';

const User = () => {
  const [searchParams] = useSearchParams();

  const makeYear = searchParams.get("makeYear");
  // handle logic based on makeYear

  ...
};

Upvotes: 11

Related Questions