3

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

0

1 Answer 1

11

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

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

4 Comments

Thank you for the response! I already tried this. Although I can get the makeYear in my component, the searchParam is immediately removed from the URL. So //user/1/cars?makeYear=2020 changes to /user/1/cars
@Frosty619 No worries. It sounds like you have some code somewhere stripping it out. Can you provide a more complete code example that does that behavior? See minimal reproducible example? If possible could you create a running codesandbox that reproduces the issue that we could inspect and debug live?
@Frosty619 are you setting your search string when navigating? the useNavigate() hook seems to allow this, according to this article at least: ultimatecourses.com/blog/…
You were right, there was some other code that was stripping the query param out. Thank you for your help!

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.