5

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?

Pavel Horyna
  • 360
  • 1
  • 5
  • 17

1 Answers1

2

How about creating this array dynamically as a variable that you can iterate and export.

export const routesList = [
{
    path: '/',
    element: <Layout />,
    children: [
        {
            path: "Clients",
            element: <Clients />,
        },
    ],
}];

Render it within your Routes:

{routesList.map((_route, i) => {
    return (
        <Route
            key={i}
            path={_route.path}
            element={_route.element}
        >
            {_route.children && children.map((_childRoute, j) => {
                <Route
                    key={j}
                    path={_childRoute.path}
                    element={_childRoute.element}
                ></Route>
            })}
        </Route>
    );
})}

Afterwards, import it from any other child component.

import { routesList } from 'ParentComponent';
Nick Brown
  • 36
  • 6