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

utilities

76 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

createPath return type

createPath returns a combined URL path string created from the pathname, search, and hash components passed as parameters.

createPath function signature and parameters

createPath is a utility function that creates a string URL path from given pathname, search, and hash components. It accepts a single parameter which is a Partial<Path> object with optional properties: pathname (defaults to "/"), search (defaults to ""), and hash (defaults to ""). The function returns a combined URL path string.

createRoutesStub return type

createRoutesStub returns a React component that renders the test router.

createRoutesStub purpose

createRoutesStub creates a React component that renders the provided routes in a test-friendly React Router context. It is used to unit test components that rely on router context, such as loaderData, actionData, and route matches.

createRoutesStub _context parameter

The _context parameter of createRoutesStub is an optional RouterContextProvider that supplies application context values to route middleware, loaders, and actions.

createRoutesStub function signature

createRoutesStub is a function that takes two parameters: routes (a StubRouteObject array) and an optional _context (RouterContextProvider). It returns a React component that renders the test router.

createRoutesStub routes parameter

The routes parameter of createRoutesStub accepts an array of StubRouteObject instances that define the route objects to render in the test router.

createRoutesFromElements parameters

createRoutesFromElements accepts two parameters: children (the React children to convert into a route config, required) and parentPath (the path of the parent route used to generate unique IDs, used for internal recursion and not intended for application developers).

createRoutesFromElements return type

createRoutesFromElements returns an array of RouteObject that can be used with a DataRouter.

createRoutesFromElements example usage

const routes = createRoutesFromElements( <> <Route index loader={step1Loader} Component={StepOne} /> <Route path="step-2" loader={step2Loader} Component={StepTwo} /> <Route path="step-3" loader={step3Loader} Component={StepThree} /> </> ); const router = createBrowserRouter(routes); function App() { return <RouterProvider router={router} />; } This example shows how to use createRoutesFromElements to define routes as JSX elements, convert them to route objects, create a browser router, and provide it to the application.

createRoutesFromElements converts JSX elements to route config

createRoutesFromElements is a utility that creates route objects from JSX elements instead of arrays of objects. It takes React children as JSX Route elements and converts them into an array of RouteObject that can be used with a DataRouter.

createSearchParams function signature and parameters

createSearchParams takes an optional parameter init of type URLSearchParamsInit with a default value of an empty string, and returns a URLSearchParams object. The signature is: function createSearchParams(init: URLSearchParamsInit = ""): URLSearchParams

createSearchParams array values example

Instead of using new URLSearchParams([["sort", "name"], ["sort", "price"]]), you can use createSearchParams({ sort: ["name", "price"] }) to create multiple values for the same query parameter key.

createSearchParams return type

createSearchParams returns a URLSearchParams object containing the initialized search parameters.

createSearchParams supports arrays as object values

createSearchParams is identical to new URLSearchParams(init) except it supports arrays as values in the object form of the initializer. When you pass an object with array values, each array element becomes a separate query parameter value for that key, instead of requiring a tuple initializer format.

data() function signature

The data() function has the signature: function data<D>(data: D, init?: number | ResponseInit). It takes a generic data parameter of any type and an optional init parameter that can be either a status code number or a ResponseInit object. It returns a DataWithResponseInit instance.

data() usage in action function

The data() utility is commonly used in action functions to return data with custom response headers and status codes. For example: return data(item, { headers: { "X-Custom-Header": "value" }, status: 201 });

data() return type

The data() function returns a DataWithResponseInit instance containing the data and response init configuration.

data() parameter: init

The init parameter is optional and can be either a status code (number) or a ResponseInit object to be included in the response. It allows setting headers and status on the response.

data() parameter: data

The data parameter is the data to be included in the response. It can be of any type.

data() utility creates responses with headers and status

The data() utility function creates responses that contain headers and status without forcing serialization into an actual Response object. It accepts data and optional ResponseInit configuration.

generatePath encoding example with spaces

generatePath('/files/:name', { name: 'a b' }) returns '/files/a%20b', showing that spaces are percent-encoded.

generatePath encoding example with plus sign

generatePath('/releases/:v', { v: '1.0.0+1' }) returns '/releases/1.0.0+1', showing that plus signs are kept as-is per RFC 3986.

generatePath import statement

generatePath is imported from the react-router package: import { generatePath } from 'react-router';

generatePath function signature

The generatePath function has the signature: function generatePath<Path extends string>(originalPath: Path, params: GeneratePathParams<Path> = {} as any): string. It takes an original path template string and an optional params object, returning a string with parameters interpolated into the path.

generatePath parameter interpolation

generatePath replaces path parameters like :id with values from the params object. For example, generatePath('/users/:id', { id: '123' }) returns '/users/123'.

generatePath percent-encoding rules

Param values are percent-encoded for use in path segments. Characters that would change URL structure (/, ?, #, %, whitespace, non-ASCII) are escaped. Characters allowed literally in path segments per RFC 3986 ($ & + , ; = : @) are kept as-is. Splat (*) values are encoded per segment while preserving / separators.

href parameter encoding behavior

The href utility percent-encodes param values for use in path segments. Characters that would change URL structure (/, ?, #, %, whitespace, non-ASCII) are escaped. Characters allowed literally in a path segment per RFC 3986 ($, &, +, comma, semicolon, equals, colon, @) are kept as-is. This differs from query-string encoding where those characters are delimiters and must be escaped. Splat (*) values are encoded per segment while preserving / separators.

href utility example with optional parameter

Example: const h = href("/:lang?/about", { lang: "en" }) returns "/en/about". This shows using an optional parameter with href.

href utility with Link component

The href utility can be used with the Link component: <Link to={href("/products/:id", { id: "abc123" })} />. This passes the resolved URL to the Link's to prop.

href utility function signature

The href utility function has the signature: function href<Path extends keyof Args>(path: Path, ...args: Args[Path]): string. It takes a route path and route params as arguments and returns a resolved URL path string.

href utility purpose

The href utility returns a resolved URL path for the specified route. It is used to generate proper URLs when working with routes that have parameters.

isCookie utility function

isCookie is a utility function that returns true if a value is a React Router Cookie object, otherwise returns false. It takes one parameter: object, which is the value to check.

ErrorResponse properties accessible

When isRouteErrorResponse returns true, the error object has properties including status (HTTP status code), statusText (HTTP status text), and data (error response data).

isRouteErrorResponse function signature

isRouteErrorResponse is a utility function with signature: function isRouteErrorResponse(error: any): error is ErrorResponse. It takes one parameter named error of type any, and returns a boolean type guard that narrows the type to ErrorResponse.

isRouteErrorResponse purpose

isRouteErrorResponse checks if a given error is an ErrorResponse generated from a 4xx/5xx Response thrown from an action or loader function.

isRouteErrorResponse example usage

Example showing how to use isRouteErrorResponse in an ErrorBoundary component: ```tsx import { isRouteErrorResponse } from "react-router"; export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) { if (isRouteErrorResponse(error)) { return ( <> <p>Error: `${error.status}: ${error.statusText}`</p> <p>{error.data}</p> </> ); } return ( <p>Error: {error instanceof Error ? error.message : "Unknown Error"}</p> ); } ``` This example demonstrates checking if an error is a route error response and accessing its status, statusText, and data properties.

isSession utility function

isSession returns true if a value is a React Router Session object, otherwise false. It takes one parameter: object, which is the value to check. This utility is available in framework and data modes.

isSession parameters and return type

isSession(object) takes one parameter named object (the value to check) and returns a boolean: true if the value is a React Router Session object, false otherwise.

matchPath pattern parameter

The pattern parameter can be a string or a PathPattern object. If a string is provided, it is treated as a pattern with caseSensitive set to false and end set to true.

matchPath performs pattern matching on URL pathname

matchPath performs pattern matching on a URL pathname and returns information about the match.

matchPath function signature

matchPath is a generic function that takes a pattern and pathname and returns a PathMatch object or null. The signature is: function matchPath<Path extends string>(pattern: PathPattern<Path> | Path, pathname: string): PathMatch<ParamParseKey<Path>> | null

matchPath pathname parameter

The pathname parameter is a string representing the URL pathname to match against the pattern.

matchPath return value

matchPath returns a PathMatch object if the pattern matches the pathname, or null if there is no match.

matchRoutes purpose

matchRoutes matches the given routes to a location and returns the match data.

matchRoutes return value

matchRoutes returns an array of matched RouteMatch objects, or null if no matches were found. The return type is RouteMatch<string, RouteObjectType>[] | null.

matchRoutes basename parameter

The basename parameter of matchRoutes is optional and defaults to "/". It is a base path to strip from the location before matching.

matchRoutes basic usage example

import { matchRoutes } from "react-router"; let routes = [{ path: "/", Component: Root, children: [{ path: "dashboard", Component: Dashboard, }] }]; matchRoutes(routes, "/dashboard"); // [rootMatch, dashboardMatch]

matchRoutes locationArg parameter

The locationArg parameter of matchRoutes accepts either a string path or a partial Location object. It has type Partial<Location> | string.

matchRoutes routes parameter

The routes parameter of matchRoutes is an array of route objects to match against. It has type RouteObjectType[].

matchRoutes function signature

matchRoutes is a function with signature: function matchRoutes<RouteObjectType extends RouteObject = RouteObject>(routes: RouteObjectType[], locationArg: Partial<Location> | string, basename = "/"): RouteMatch<string, RouteObjectType>[] | null. It takes route objects, a location, and an optional basename parameter.

parsePath return value

parsePath returns a Partial<Path> object containing the parsed pathname, search, and hash components extracted from the input URL path string.

parsePath parameter: path

The path parameter is a required string argument that represents the URL path to parse.

parsePath function signature

parsePath is a utility function that takes a string URL path and returns a Partial<Path> object. The signature is: function parsePath(path: string): Partial<Path>

redirect example in loader

import { redirect } from "react-router"; export async function loader({ request }: Route.LoaderArgs) { if (!isLoggedIn(request)) throw redirect("/login"); // ... }

redirect works in framework and data modes

The redirect utility is available in both framework mode and data mode.

redirect utility basic usage

The redirect utility creates a redirect Response object with a status code and Location header. It defaults to 302 Found status code. It is thrown from loaders to redirect users to a different URL.

redirect function signature and parameters

redirect(url, init) takes two parameters: url (the URL to redirect to) and init (the status code or a ResponseInit object to be included in the response). It returns a Response object with the redirect status and Location header.

redirect accepts absolute URLs and external domains

The redirect utility accepts absolute URLs and can navigate to external domains. Applications should validate any user-supplied inputs to redirects to prevent open redirect vulnerabilities.

redirectDocument parameters

redirectDocument accepts two parameters: (1) url - the URL to redirect to, and (2) init - the status code or a ResponseInit object to be included in the response.

Give your agent this brain