Skip to content

Instantly share code, notes, and snippets.

@denisborovikov
Created September 17, 2022 02:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save denisborovikov/3e6e772d9d1897c150639872467d214f to your computer and use it in GitHub Desktop.
Save denisborovikov/3e6e772d9d1897c150639872467d214f to your computer and use it in GitHub Desktop.
const routes = {
home: '/',
transactions: '/transactions',
transactionDetails: '/transactions/:uuid',
}
const urls: Record<
keyof typeof routes,
{ get: (params?: any) => string; route: string }
> = new Proxy(routes, {
get(target: any, propKey: any) {
const route = target[propKey]
return {
get: (params: Record<string, string>, query?: Record<string, string>) =>
generatePath(route, params) +
(query ? `?${new URLSearchParams(query).toString()}` : ''),
route,
}
},
})
// <Route exact path={urls.home.route}>
// <HomePage />
// </Route>
// <Link href={urls.transactionDetails.get({ uuid: 123 } )} /> // /transactions/123
@nelsonmestevao
Copy link

nelsonmestevao commented Sep 19, 2022

How would you go about relative paths? 🤔

(In the Link component when you need a subsection of it).

@denisborovikov
Copy link
Author

In our case, the route's structure is flat. We don't have nested routes and don't use relative paths.

@nelsonmestevao
Copy link

Thank you 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment