I'm trying to add an optional query parameter to the end of a path, so the URL woukd 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. However, the query parameter, however 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)
CodePudding user response:
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
...
};