Home > other >  Passing Multiple parameters as catch them
Passing Multiple parameters as catch them

Time:01-25

I'm trying to pass 'slug' in the URL by adding 'id' and 'type'.

Code:

`/${category.slug}?cid=${category._id}&type=${category.type}`   
 <Route path="/:slug" element={<ProductListPage />} />

URL

http://localhost:3000/Samsung-3whQlbAYpm?cid=61ed050cab3efd275d49efd6&type=store

Problem : However, in the useParam() I received only slug not addition parameters such as 'cid' and 'type'

For example,

let params = useParams();

Its params have only 'slug' value which is 'Samsung-3whQlbAYpm'

How can I get addition value ?

CodePudding user response:

The useParams hook only gets you the defined route params from the path part of the URL. If you want to access the queryString then use the useSearchParams hook from react-router-dom.

const [searchParams] = useSearchParams();

const cid = searchParams.get("cid");
const type = searchParams.get("type");

If you happen to still be using react-router-dom v5 then use the location object to get the search string to be passed to a URLSearchParams constructor.

const { search } = useLocation();
const searchParams = new URLSearchParams(search);
  •  Tags:  
  • Related