Access useParams hook from Navbar or static component in react-router v6

Viewed 23

How can I get a Navbar at the top of every page to have access to react-router useParams hook? With the below code User will have userId returned, but Nav gets an empty object.

It looks like a component (element) needs to be rendered inside a Route to use this hook but in v6 all routes are "exact" so I don't see a way for a static component to render on every path.

<BrowserRouter>
  <Nav /> // How does this component show on every page and get access to route params?
  <Routes>
    <Route path='/' element={<Home />} />
    <Route path='/user/:userId' element={<User />} />
    <Route path='/profile' element={<Profile />} />
  </Routes>
</BrowserRouter>
1 Answers

If you want the Nav component to render with each page/route and able to access any route path params then you can create a Layout Route that renders the Nav component and an Outlet component for the nested routes to render their content into.

Example:

import { Outlet } from 'react-router-dom';

const Layout = () => (
  <>
    <Nav />
    <Outlet />
  </>
);

...

<BrowserRouter>
  <Routes>
    <Route element={<Layout />}>
      <Route path='/' element={<Home />} />
      <Route path='/user/:userId' element={<User />} />
      <Route path='/profile' element={<Profile />} />
    </Route>
  </Routes>
</BrowserRouter>
Related