React router v6 get all routes

Viewed 254

Let's say I have a url path 'clients/devices/2', the routes are defined like this:

 <Routes>
    <Route path="/" element={<Layout />}>
      <Route path="clients" element={<Clients />} />
      <Route path="devices" element={<Devices />}>
        <Route path=":deviceId" element={<Device />} />
      </Route>
    </Route>
 </Routes>

Now, I'm at said url 'clients/devices/2', and I want to get an array of all the routes involved, something like this:

[
  {
    element: <Layout />,
    path: "/",
    children: [
     {
       path: "Clients",
       element: <Clients />,
     },
    ],
  },
 etc etc
];

Is there a way to achieve this with some native react-router methods? I'm trying to make breadcrumbs for my app, where I need exactly this kind of routes info. It's baffling for me that such a key functionality seems not implemented in react-router, or am I missing something?

Right now I'm working with useLocation, where I parse the pathname string and try to match it againt some route enum I created, then go from there, but that seems terribly inconvenient.

What is the best way to approach this?

0 Answers
Related