Last active
March 12, 2023 21:51
-
-
Save strlns/8c8f7fd0d6438c89392337fa4cbc5fe1 to your computer and use it in GitHub Desktop.
createBrowserRouter with Intellisense suggestions / exhaustive union types for route IDs
This file contains hidden or 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
import { RouterProvider } from "react-router"; | |
import { createBrowserRouter } from "react-router-dom"; | |
import { routes } from "routes"; | |
function App() { | |
//... | |
const router = createBrowserRouter(routes); |
This file contains hidden or 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
import Home from "pages/Home"; | |
import RouteError from "components/Error/RouteError"; | |
import { RouteObject } from "react-router"; | |
const ROUTES = [ | |
{ | |
path: "/", | |
element: <Home />, | |
errorElement: <RouteError />, | |
id: "Home", | |
}, | |
//... | |
] as const; | |
//alternatively, just use | |
//export const routes = [...ROUTES].slice() as RouteObject[]; | |
export const routes = [...ROUTES] as Mutable<typeof ROUTES> as RouteObject[]; | |
type RouteID = (typeof ROUTES)[number]["id"]; | |
type RoutePath = (typeof ROUTES)[number]["path"]; | |
type RoutePaths = { | |
[key in RouteID]: RoutePath; | |
}; | |
export const routePaths: RoutePaths = Object.fromEntries( | |
ROUTES.map((route) => [route.id, route.path]) | |
) as RoutePaths; | |
type Mutable<T extends object> = { | |
-readonly [K in keyof T]: T[K]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment