Making routes in React maintainable

Viewed 47

I have a router with paths. Currently we have an enum with paths like:

enum Paths {
    home: '/home',
    finding: '/finding',
}

and I create links "manually" like so:

navigate(`${Paths.home}${Paths.finding}`)

This works but is not maintainable at all.

My other idea was:

paths: {
  path: '/',
  home: {
    path: '/home',
      finding: {
        path: '/finding',
        params: {
          id: string
        },
        edit: {
          path: '/edit'
        }
      }
  }
}

navigate(paths.home.finding)

but this quickly falls apart, since my routes are home/finding/id/edit and I'd need to throw a wildcard into an object/break it apart. So not maintainable.

I think the best solution is to simply keep the routes one under the other with similar parts shared like:

userBase = '/home'
userFinding = `${userBase}/finding/id`
userFindingEdit = `${userFinding}/edit`

But this is kind of pointless with nested Routes.

<Route path={Paths.home} element={...}>
  <Route path={Paths.finding}>
    <Route path={Paths.id}>
      <Route path={Paths.edit} element={<EditFinding />} />
      <Route path={Paths.empty} element={<Finding />} />
    </Route>
  </Route>
</Route>

If there was a way to extract all possible routes combination from react router with a hook that would be perfect. Do you have any other suggestions?

Example https://codesandbox.io/s/nice-frost-pjhkmd?file=/src/App.tsx

0 Answers
Related