When using React Router v5, it was possible to get the path (pattern) for that route using useRouteMatch
.
const { path } = useRouteMatch();
React Router v6 offers a similar hook, useMatch
; however this expects to receive the pattern you want to match against.
I would use the React Router v5 hook to generate routes by combining the current path with known params.
As an example, if I am on the product page of an eCommerce application (let's assume /en/product/:id
) and there are links to related products (/en/product/1
, /en/product/2
...etc), I would previously have been able to do:
const MyComponent = () => {
const { path } = useRouteMatch();
return (
<div>
<Link to={generatePath(path, { id: 1 })}>Related Product 1</Link>
<Link to={generatePath(path, { id: 2 })}>Related Product 2</Link>
</div>
);
};
Since /en/product
comes from an API and is not declared anywhere in the code, I would want the URLs to be updated based on the current path. If the user is on /es/producto
, then the links would automatically be updated to /es/producto/1
.
I have seen solutions on SO where it was suggested to use matchRoutes
, however it feels highly inefficient, especially since the routes are dynamically generated from an external API.
const useCurrentPath = () => {
const location = useLocation()
const [{ route }] = matchRoutes(routes, location)
return route.path
}
I have created a small demo to illustrate how this used to work: