2

Is there any way in React-Router to console.log the path like so "users/:userId" (not "users/123") from the root component every time the route changes from anywhere in the app?

So for we have this, but can only print "users/123":

// ...

export default function App() {
  useEffect(() => {
    const unlisten = history.listen((location, action) => {
      console.log(
        `${action} ${location.pathname}${location.search}${location.hash}`
      );
    });

    return () => {
      unlisten();
    };
  }, []);

  // ...
}
Alex Nault
  • 613
  • 7
  • 23
  • Does this answer your question? [react-router v6: get path pattern for current route](https://stackoverflow.com/questions/66265608/react-router-v6-get-path-pattern-for-current-route) – Jax-p Jul 21 '22 at 15:21

1 Answers1

0

You need to access the match object instead of the location object. match will have the path pattern string used.

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

Use the useRouteMatch hook without any arguments to return the match object of the current <Route>.

Example:

export default function App() {
  const { path } = useRouteMatch();

  useEffect(() => {
    console.log({ path });
  }, [path]);

  // ...
}

This assumes that there is a router higher in the ReactTree than App providing a routing context.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • We're looking to have a single useEffect at the root component that would match everything, so this won't work unfortunately :/ – Alex Nault Jul 21 '22 at 17:26
  • @AlexNault I see. Yeah, just tested this and it appears `useRouteMatch` can only grab matches from above itself. Can you provide a more complete code example that includes some routes? – Drew Reese Jul 21 '22 at 18:14