react-router v6: get path pattern for current route

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);

  (...)
};

this is works for me easily

first of all import uselocation from react-router-dom

import { useLocation } from "react-router-dom"

then

const location = useLocation();
console.log(location.pathname);