Reputation: 297
<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
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
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 ...;
};
Upvotes: 3
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