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
You need to use
useParams
from the documentationAccording to official react router documentation useParams hook can only access the params of a
Route
within theRoutes
component. The problem is theMenu
component is outside of the Routes component.just wrap the
<Menu />
component like below and try.also see:
Get id using useParams hook in functional component – react router dom v6