'React: How to get current Route path on each route change? React-router v5

The following code is giving base route instead of nested routes or I can say the current route

function test() {
  const route = useRouteMatch();
  useEffect(() => {
    console.log(route);
  }, [route]);
}

I need path here like 'base/user/:id' not 'base/user/:123'



Solution 1:[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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Drew Reese