skip to Main Content

I tried to find it, but I couldn’t do it. I tested many results but the effects were disappointing (sometimes like my work :P)

So I have this structure of application:

<BrowserRouter>
  <Menu/>
  <Routes>
    <Route path="/business/:id" element={<SomePage />} />
  </Routes>
</BrowserRouter>

In SomePage component I can use useParms and I see this id like object {id: 6} – it’s fine and makes sense. But I have a case when I have to extract this id in Menu component and useParams returns:

{
  *: "business/6"
}

But I would like to get object:

{
  id: 6
}

I tried to use matchPath, useMatch, useResolvedPath, and others but I didn’t have any special effects…

2

Answers


  1. You need to use useParams from the documentation

    Login or Signup to reply.
  2. According to official react router documentation useParams hook can only access the params of a Route within the Routes component. The problem is the Menu component is outside of the Routes component.

    just wrap the <Menu /> component like below and try.

    <Routes>
        <Route path="/business/:id" element={<SomePage />} />
        <Route element={<Menu />} />
     </Routes>
    

    also see:
    Get id using useParams hook in functional component – react router dom v6

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search