new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

React Router · API · all subjects

routes

42 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Routes component signature

The Routes component is a function that takes RoutesProps and returns React.ReactElement or null. Its signature is: function Routes({ children, location }: RoutesProps): React.ReactElement | null

Routes basic example

import { Route, Routes } from "react-router"; <Routes> <Route index element={<StepOne />} /> <Route path="step-2" element={<StepTwo />} /> <Route path="step-3" element={<StepThree />} /> </Routes>

Routes children prop

The children prop of Routes accepts nested Route elements.

Routes location prop

The location prop of Routes accepts a Location object to match against. It defaults to the current location if not provided.

Routes component purpose

The Routes component renders a branch of Route elements that best matches the current location. These routes do not participate in data loading, action, code splitting, or any other route module features.

createHashRouter opts.future parameter

The opts.future option enables future flags for the router.

createHashRouter opts.window parameter

The opts.window option is a Window object override that defaults to the global window instance.

createHashRouter should not be held in React state

Data routers created with createHashRouter should not be held in React state. You should create your router once outside of the React tree and pass it to <RouterProvider>. You can use patchRoutesOnNavigation to add additional routes programmatically.

patchRoutesOnNavigation use case: patching children into existing route

You can use patchRoutesOnNavigation to patch children into an existing route by calling patch with the parent route's id and an array of new routes. For example: patch('root', [route]) adds a route as a child of the route with id 'root'.

patchRoutesOnNavigation with parameterized routes

When routes contain parameters (dynamic or splat), React Router will call patchRoutesOnNavigation even after a match is found because there might be a not-yet-discovered route that scores higher. To optimize this, you can maintain a cache of previously seen paths to avoid over-fetching: let discoveredRoutes = new Set(); if (discoveredRoutes.has(path)) { return; } discoveredRoutes.add(path);

patchRoutesOnNavigation use case: patching root-level routes

To patch a new route to the top of the tree without a parent, pass null as the routeId: patch(null, [route]) adds a route as a sibling of existing root routes.

patchRoutesOnNavigation interrupted by later navigation

If in-progress execution of patchRoutesOnNavigation is interrupted by a later navigation, then any remaining patch calls in the interrupted execution will not update the route tree because the operation was cancelled.

createHashRouter signature and return type

createHashRouter is a function that takes routes: RouteObject[] and optional opts: DOMRouterOpts, and returns a DataRouter. The function signature is: function createHashRouter(routes: RouteObject[], opts?: DOMRouterOpts): DataRouter

createHashRouter manages application path via URL hash

createHashRouter creates a new data router that manages the application path via the URL hash property. Data Routers should not be held in React state and should be created once outside of the React tree, then passed to <RouterProvider>.

createHashRouter opts.basename parameter

The opts.basename option is a string that specifies the basename path for the application.

createBrowserRouter patchRoutesOnNavigation example patching root siblings

Example of patching new root-level routes by passing null as routeId: const router = createBrowserRouter([{ id: "root", path: "/", Component: RootComponent }], { async patchRoutesOnNavigation({ patch, path }) { if (path === "/root-sibling") { let route = await getRootSiblingRoute(); patch(null, [route]); } } });

createBrowserRouter manages application path via History API

createBrowserRouter creates a data router that manages the application path via history.pushState and history.replaceState from the History API.

createBrowserRouter signature and return type

createBrowserRouter is a function with signature: function createBrowserRouter(routes: RouteObject[], opts?: DOMRouterOpts): DataRouter. It returns an initialized DataRouter that should be passed to RouterProvider. The router should be created outside of the React tree and not held in React state.

createBrowserRouter routes parameter

The routes parameter is an array of RouteObject[] representing the application routes.

createBrowserRouter hydrationData example

Example of passing hydration data: const router = createBrowserRouter(routes, { hydrationData: { loaderData: { root: "ROOT DATA" } } });

createBrowserRouter opts.future

The opts.future option accepts future flags to enable for the router.

createBrowserRouter opts.hydrationData

The opts.hydrationData option allows you to pass in hydration data from server-render when opting-out of automatic hydration. It typically includes loaderData (keyed by routeId with server loader data as values), and may also include errors and actionData. This is almost always a subset of data from the StaticHandlerContext value obtained from StaticHandler's query method.

createBrowserRouter hydrationData partial hydration

In advanced use cases such as Framework Mode's clientLoader, you can include loaderData for only some routes that were loaded/rendered on the server. This allows hydrating some routes while showing a HydrateFallback component and running loaders for other routes during hydration. A route loader will run during hydration if no hydration data is provided, or if the loader.hydrate property is set to true.

createBrowserRouter instrumentation object structure

An instrumentation object has a router method that receives an instrument function to wrap navigate and fetch operations, and a route method that receives instrument and id parameters to wrap middleware, loader, and action operations.

createBrowserRouter opts.patchRoutesOnNavigation

The opts.patchRoutesOnNavigation option accepts a function for lazily defining portions of the route tree on navigations. This is for advanced use cases where you cannot provide the full route tree up-front. The function is called anytime React Router is unable to match a path, and receives an object containing path, partial matches, and a patch function to add routes to the tree at a specific location. It is executed during the loading portion for GET requests and during the submitting portion for non-GET requests.

createBrowserRouter patchRoutesOnNavigation use case examples

patchRoutesOnNavigation can be used to: patch children into an existing route by passing the parent route id to patch(), patch new root-level routes by passing null as the routeId to patch(), perform asynchronous matching to lazily fetch entire sections of the application, and co-locate route discovery with route definition using the handle field.

createBrowserRouter patchRoutesOnNavigation route parameters consideration

Because React Router uses ranked routes, when only a partial route tree is known, routes with parameters (dynamic or splat) will trigger patchRoutesOnNavigation to be called again after matching to confirm the best match has been found, since a not-yet-discovered route might score higher. For expensive patchRoutesOnNavigation implementations, you should maintain a cache of previously seen paths to avoid over-fetching.

createBrowserRouter opts.window

The opts.window option allows you to override the Window object. It defaults to the global window instance.

createBrowserRouter data strategy example

Example of overriding the default data strategy: const router = createBrowserRouter(routes, { async dataStrategy({ matches, request, runClientMiddleware }) { const matchesToLoad = matches.filter((m) => m.shouldCallHandler()); const results = {}; await runClientMiddleware(() => Promise.all(matchesToLoad.map(async (match) => { results[match.route.id] = await match.resolve(); }))); return results; } });

createBrowserRouter getContext example

Example of using getContext to provide a router context: const router = createBrowserRouter(routes, { getContext() { let context = new RouterContextProvider(); context.set(apiClientContext, getApiClient()); return context; } });

createBrowserRouter patchRoutesOnNavigation example patching children

Example of patching children into an existing route: const router = createBrowserRouter([{ id: "root", path: "/", Component: RootComponent }], { async patchRoutesOnNavigation({ patch, path }) { if (path === "/a") { let route = await getARoute(); patch("root", [route]); } } });

Data Routers documentation section

React Router documentation has a section titled 'Data Routers' which covers router APIs related to data handling. This section is order 5 in the documentation hierarchy.

Basic routes.ts example structure

Example of a basic routes.ts configuration: ```tsx import { type RouteConfig, route, } from "@react-router/dev/routes"; export default [ route("some/path", "./some/file.tsx"), ] satisfies RouteConfig; ``` The route() function takes a pattern and a module file path. The configuration is exported as default and satisfies the RouteConfig type.

route() helper function

The route() helper function from @react-router/dev/routes creates a route config entry. It takes a path pattern as the first argument and a module file path as the second argument.

index() helper function for index routes

The index() helper function from @react-router/dev/routes creates a route config entry for an index route.

layout() helper function for layout routes

The layout() helper function from @react-router/dev/routes creates a route config entry for a layout route.

prefix() helper function for path prefix

The prefix() helper function from @react-router/dev/routes adds a path prefix to a set of routes without needing to introduce a parent route.

relative() helper function for relative paths

The relative() helper function from @react-router/dev/routes creates a set of route config helpers that resolve file paths relative to the given directory. It is designed to support splitting route config into multiple files within different directories.

RouteConfig type

RouteConfig is a type imported from @react-router/dev/routes. Routes configuration should be an array of objects satisfying the RouteConfig type.

flatRoutes() for file-based routing

The flatRoutes() function from @react-router/fs-routes enables file system routing convention, allowing routes to be defined via file naming conventions rather than explicit configuration in routes.ts.

File-based routing with flatRoutes example

Example of using file-based routing with flatRoutes(): ```ts import { type RouteConfig } from "@react-router/dev/routes"; import { flatRoutes } from "@react-router/fs-routes"; export default flatRoutes() satisfies RouteConfig; ``` This enables automatic route configuration based on file system conventions instead of manual configuration.

react-router routes command

The 'react-router routes' command prints the routes in the app to the terminal in JSX format by default. Use the --json flag to output routes in JSON format. Available flags are: --config/-c (string), --json (boolean, default false), --mode/-m (string).

Give your agent this brain