Search code examples
javascriptreactjsreact-routerreact-router-dom

Determine Which Route Was Resolved


Given routes like this:

<Routes>
  <Route element={<MainLayout />}>
    <Route path="foo/:token" element={<Foo />} />
    <Route path=":token" element={<Bar />}>
      <Route path=":id" element={<Baz />}>
    <Route>
  </Route>
</Routes>

How can MainLayout know which route was resolved? I need to know if it was within the route tree with path=":token".

useMatch('/:token/*') does not work because it matches on path foo/123, which resolves to the path="foo/:token" route.

I can't figure out what useResolvedPath does or how I could use it. I just seems to echo the input param.

I can't use const { token } = useParams() since both routes have a param named token.

Ideas?


Solution

  • I was thinking about this wrong, and my question did not explain the context well enough to spot it.

    MainLayout contains global nav elements that I want to be slightly different for different routes. Rather than have MainLayout look outward at the route, the router setup should tell MainLayout what to do. Like this:

    <Routes>
      <Route element={<MainLayout />}>
        <Route path="foo/:token" element={<Foo />} />
      </Route>
      <Route element={<MainLayout someParam={paramValue} />}>
        <Route path=":token" element={<Bar />}>
          <Route path=":id" element={<Baz />}>
        <Route>
      </Route>
    </Routes>
    

    Where MainLayout uses paramValue to behave differently.