mycodegoesKABOOM
mycodegoesKABOOM

Reputation: 297

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.

Upvotes: 8

Views: 6154

Answers (3)

Fahad Ali
Fahad Ali

Reputation: 115

react-router v6: The most easiest way to get an id from url. Caution(This only works if your component is a child of a componentThis only works if your component is a child of a component)

import { useParams } from "react-router-dom";
const { id } = useParams();

return(
    <>
        <h2> This is useParams id = {id} </h2>
    </>
);

Upvotes: -2

Drew Reese
Drew Reese

Reputation: 202864

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

Upvotes: 3

Fiodorov Andrei
Fiodorov Andrei

Reputation: 2018

You can use matchPath:

react-router v6:

const match = matchPath({ path: "/users/:id" }, "/users/123");

react-router v5:

const match = matchPath("/users/123", {
  path: "/users/:id",
  exact: true,
  strict: false
});

Upvotes: 8

Related Questions