fenok / react-router-typesafe-routes

Comprehensive and extensible type-safe routes for React Router v6 with first-class support for nested routes and param validation.
MIT License
145 stars 3 forks source link

Get absolute path without indeterminate stars #21

Closed JakeHaitsma closed 1 year ago

JakeHaitsma commented 1 year ago

Hello,

Thanks for your work on this, I believe it can really help my current project. My organization uses sub-routers to add shared wrappers/organize code specific to a particular kind of entity.

For example:

<Routes>
  <Route path={ROUTES.HOME.path} element={<HomePage />} />
  <Route path={ROUTES.USERS.path} element={<UserRouter />} />
</Routes>

UserRouter would render the following:

<Routes>
  <Route path={ROUTES.USERS.$.LIST.path} element={<UserListPage />} />
  <Route path={ROUTES.USERS.$.DETAILS.path} element={<UserDetailsPage />} />
</Routes>

ROUTES would look something like this:

export const ROUTES = {
  HOME: route(''),
  USERS: route(
    'users/*',
    {},
    {
      LIST: route(''),
      DETAILS: route(':id'),
    }
  ),
};

How would one navigate to ROUTES.USERS.LIST.path while excluding the indeterminate star introduced by USERS route? Does this project support that? relativePath omits it, as noted in the README, but I'm curious if this use case is supported.

console.log(ROUTES.USERS.LIST.path); // prints `users/*`, I'm looking to just print `users/`, potentially at depth (nested routers within nested routers)
fenok commented 1 year ago

Hello and thanks for using the library!

If I understood your use case correctly, you need to use either ROUTES.USERS.LIST.buildUrl({}), which will print "/users", or ROUTES.USERS.LIST.buildRelativeUrl({}), which will print "users". The buildUrl and buildRelativeUrl functions are intended to be used to produce actual paths for navigation (for instance, they can be used in <Link/> components).

In contrast, path and relativePath are path patterns. For instance, they can be used in <Route/> components.

If you specifically want a trailing slash (as in "users/") - no, that's not supported, because trailing slashes don't do anything in React Router (though you can add it like this: `${ROUTES.USERS.LIST.buildRelativeUrl({})}/`). If that's the case, can you please explain why you need this?

Please let me know if I misunderstood something.