3

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.

ali safaeyan
  • 65
  • 1
  • 11
  • The route for that URL would be `} />`. 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? – Drew Reese Jan 09 '23 at 07:59
  • 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 object – ali safaeyan Jan 09 '23 at 08:04
  • Can you [edit] the post to include a more complete [mcve] 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. – Drew Reese Jan 09 '23 at 08:08
  • Thank you. And what params are you trying to read from in the component? – Drew Reese Jan 09 '23 at 08:25
  • @DrewReese c, cc , user – ali safaeyan Jan 09 '23 at 08:31
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/250962/discussion-between-drew-reese-and-ali-safaeyan). – Drew Reese Jan 09 '23 at 08:31

1 Answers1

1

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"

  ...

};
Drew Reese
  • 165,259
  • 14
  • 153
  • 181