Is it possible to get the path pattern for the currently matched route? Example:
<Route
path=":state/:city*"
element={
<Page />
}
/>
// Page.jsx
function Page() {
...
// usePathPattern doesn't actually exist
const pathPattern = usePathPattern(); // pathPattern = ":state/:city*"
...
}
I know I can use useMatch to check if the current location matches a specific path pattern, but then the component has to know what the path pattern is.
From within the context of a Route you can get the path via several methods layed out in the docs.
My issue was slightly different in that I needed the path outside the context of the Route and came to the below solution that should also work for you:
import {
matchPath,
useLocation
} from "react-router-dom";
const routes = [ ':state/:city', ...otherRoutes ];
function usePathPattern() {
const { pathname } = useLocation();
return matchPath( pathname, routes )?.path;
}
I'm not sure if it resolves your use case fully but in my case I used combination of useLocation and useParams. Here is the code:
import React from 'react';
import { useLocation, useParams } from 'react-router-dom';
import type { Location, Params } from 'react-router-dom';
/**
* Function converts path like /user/123 to /user/:id
*/
const getRoutePath = (location: Location, params: Params): string => {
const { pathname } = location;
if (!Object.keys(params).length) {
return pathname; // we don't need to replace anything
}
let path = pathname;
Object.entries(params).forEach(([paramName, paramValue]) => {
if (paramValue) {
path = path.replace(paramValue, `:${paramName}`);
}
});
return path;
};
export const Foo = (): JSX.Element => {
const location = useLocation();
const params = useParams();
const path = getRoutePath(location, params);
(...)
};
I made a custom hook useCurrentPath with react-router v6 to get the current path of route, and it work for me
If the current pathname is /members/5566 I will get path /members/:id
import { matchRoutes, useLocation } from "react-router-dom"
const routes = [{ path: "/members/:id" }]
const useCurrentPath = () => {
const location = useLocation()
const [{ route }] = matchRoutes(routes, location)
return route.path
}
function MemberPage() {
const currentPath = useCurrentPath() // `/members/5566` -> `/members/:id`
return <></>
}