how to get a URL parameters in react router V6?
Asked Answered
G

1

8

I have a URL like this :

"http:something/forget/reset?type=text&c=$something&cc=$something"

I want to get the parameters form this path and I used:

const params = useParams()

but it returns an empty object {}

my current route is like below:

  <Route
    path="forget/reset"
    element={<ComponentA/>}
  />

so should I define a route with parameters like below or is there a way to get multiple parameters form a url

<Route path="forget" element={<ComponentA/>}>
  <Route
    path="forget/reset/:user/:c/:cc"
    element={<ComponentA/>}
  />
</Route>

the above code also does not work.

Greenling answered 9/1, 2023 at 7:57 Comment(6)
The route for that URL would be <Route path="/forget/reset" element={<ComponentA />} />. The queryString params would be accessed in the component for that route, ComponentA. Are you saying you want/need additional/optional path parameters beyond "/forget/reset"? What paths do you actually need to match?Nuris
Hi my friend @DrewReese I have wrote it like what you say. but when I tried to get parameters with useParam hook it returns an empty objectGreenling
Can you edit the post to include a more complete minimal reproducible example for what you are trying to do overall? It's unclear if you are trying to specify, and access, more route path params, or if you are just trying to access the queryString params. A more complete code example would help here.Nuris
Thank you. And what params are you trying to read from in the component?Nuris
@DrewReese c, cc , userGreenling
Let us continue this discussion in chat.Nuris
N
18

Given:

  • URL path "/forget/reset?type=text&c=$something&cc=$something"
  • Route <Route path="forget/reset" element={<ComponentA />} />

For ComponentA to access the queryString params it should import and use the useSearchParams hook exported from react-router-dom@6.

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

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

  const type = searchParams.get("type"); // "text"
  const c = searchParams.get("c");       // "$something"
  const cc = searchParams.get("cc";      // "$something"

  ...

};
Nuris answered 12/1, 2023 at 7:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.