React-Router-Dom: Can I call `useParams()` to get path param outside of Route?

Viewed 268

I have a simple JSX

<div>
  <Header />
  <Route exact path = "/:id" component={Home}/>
  <Route exact path = "/other/:id" component={Other}/>
</div>

In the header contains the NavLinks and I want them to include the previously provided ID like...

const id = useParams().id;
const root = `/${id}`;
const Other = `/other${root}`;
<NavLink to={root} activeStyle={activeStyle} exact className="bg-link">Home</NavLink>
<NavLink to={other} activeStyle={activeStyle} exact className="bg-link">Other</NavLink>

The problem is the useParams().id returns undefined since it is not inside the route itself. Can I access this info from there?

I am using redux so I am wondering if I don't have to put it on my redux state in the router. However, I am not very good at redux yet so I would like a more direct answer if possible.

0 Answers
Related