score:1

You've got the correct hook for getting the path that was used when matching/rendering the route.

useRouteMatch

The useRouteMatch hook attempts to match the current URL in the same way that a <Route> would. It’s mostly useful for getting access to the match data without actually rendering a <Route>.

match

A match object contains information about how a <Route path> matched the URL. match objects contain the following properties:

  • params - (object) Key/value pairs parsed from the URL corresponding to the dynamic segments of the path
  • isExact - (boolean) true if the entire URL was matched (no trailing characters)
  • path - (string) The path pattern used to match. Useful for building nested <Route>s
  • url - (string) The matched portion of the URL. Useful for building nested <Link>s

The useRouteMatch hook returns a match object with the path property that is the path used for matching.

<Route path="/base/user/:id" component={Test} />

...

function Test() {
  const { path } = useRouteMatch();
  useEffect(() => {
    console.log(path); // "/base/user/:id"
  }, [path]);

  return null;
}

Edit react-how-to-get-current-route-path-on-each-route-change


Related Query

More Query from same tag