Created
July 29, 2020 23:42
-
-
Save adesurirey/f2a847138abf3c7e8e04420cd4470854 to your computer and use it in GitHub Desktop.
Centralizing routes declaration and usage in a React app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ROUTES = { | |
SHIPMENTS: "/shipments", | |
SHIPMENT: "/shipments/:id", | |
}; | |
interface RouteParams { | |
SHIPMENT: { id: number }; | |
} | |
type Routes = typeof ROUTES; | |
type Route = keyof Routes; | |
type DynamicRoute = keyof RouteParams; | |
type StaticRoute = keyof Omit<Routes, keyof RouteParams>; | |
interface BuildPath { | |
<T extends DynamicRoute>(route: T, params: RouteParams[T]): string; | |
<T extends StaticRoute>(route: T): string; | |
} | |
const buildPath: BuildPath = (route: Route, params: any = {}) => { | |
const routeElements = ROUTES[route].split("/"); | |
return routeElements.reduce((prevElement, currentElement) => { | |
const nextElement = currentElement.startsWith(":") | |
? params[currentElement.slice(1)] | |
: currentElement; | |
return `${prevElement}/${nextElement}`; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment