Skip to content
Advertisement

React Router v6 useRouteMatch equivalent

When using React Router v5, it was possible to get the path (pattern) for that route using useRouteMatch.

JavaScript

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:

JavaScript

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.

JavaScript

I have created a small demo to illustrate how this used to work:

Code Sandbox Demo

Advertisement

Answer

In react-router-dom@6 there is no replacement for the v5 useRouteMatch hook. The links and routes no longer need to be concerned with the path pattern so much as they can simply use relative routes and links. Instead of trying to access a route’s path pattern it can simply navigate relative to the currently matched path.

Example:

This navigates from "/route-a/2" to "/route-a/2/../1" or rather "/route-a/1".

JavaScript

Demo

Edit react-router-v6-useroutematch-equivalent

Fullcode:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement