Wednesday, May 15, 2024
 Popular · Latest · Hot · Upcoming
50
rated 0 times [  53] [ 3]  / answers: 1 / hits: 6429  / 2 Years ago, thu, august 11, 2022, 12:00:00

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).


More From » reactjs

 Answers
1

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

...
};

[#40] Wednesday, July 13, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nolancampbellc

Total Points: 9
Total Questions: 102
Total Answers: 101

Location: Saint Vincent and the Grenadines
Member since Mon, Jan 16, 2023
1 Year ago
nolancampbellc questions
Thu, Sep 23, 21, 00:00, 3 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
Thu, Aug 20, 20, 00:00, 4 Years ago
;