reactjsparametersreact-routerurl-parameters

how to get a URL parameters in react router V6?


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.


Solution

  • Given:

    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"
    
      ...
    
    };