'React router v6 easiest way to access params outside route

<Menu/>

<Routes>
<Route path="/" element={<HomeView />} />
<Route path="/website/:Id" element={<WebsiteView />} />
</Routes>

What is the easiest way to access Id parameter from Menu component?

UseParams can only be used in element rendered by route.

I am currently doing this:

const location = useLocation();

const Id = location.pathname.split("/")[2]

This is however not rigid enough for me I think. I want the react way of retrieving the Id Param please - no fancy solutions please, the simplest way to do this.



Solution 1:[1]

The id route match param is only available on the params object of all ancestor and descendent Route components within a Routes component.

If the Menu component is capable of using the useParams hook (and there's a way to inject params as a prop if Menu is a class component) there is a refactor you can do where Menu is rendered as part of a layout along with an Outlet component and it will then be in the route hierarchy to access the route params.

<Routes>
  <Route
    element={
      <>
        <Menu />   // <-- descendent route match params accessible here
        <Outlet /> // <-- nested routes rendered here
      </>
    }
  >
    <Route path="/" element={<HomeView />} />
    <Route path="/website/:Id" element={<WebsiteView />} />
  </Route>
</Routes>

Example Menu component:

const Menu = () => {
  const params = useParams();
  console.log("Menu", params);
  return ...;
};

Edit react-router-v6-easiest-way-to-access-params-outside-route

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Drew Reese