UNPKG

94.7 kBTypeScriptView Raw
1import { bG as RouteManifest, o as RouteModules, Q as HydrationState, a1 as DataRouteObject, a as ClientLoaderFunction, a5 as StaticHandlerContext, bH as ServerRouteModule, q as MiddlewareEnabled, c as RouterContextProvider, r as AppLoadContext, al as LoaderFunctionArgs, ac as ActionFunctionArgs, au as unstable_ServerInstrumentation, aj as HTMLFormMethod, ah as FormEncType, w as RelativeRoutingType, bh as PageLinkDescriptor, T as To, bI as History, a4 as GetScrollRestorationKeyFunction, e as RouterInit, bJ as FutureConfig$1, u as unstable_ClientInstrumentation, p as DataStrategyFunction, a0 as PatchRoutesOnNavigationFunction, s as NavigateOptions, a6 as Fetcher, K as RouteObject, n as Router, v as SerializeFrom, B as BlockerFunction, L as Location, bK as CreateStaticHandlerOptions$1, a2 as StaticHandler } from './instrumentation-DvHY1sgY.js';
2import * as React from 'react';
3
4interface Route {
5 index?: boolean;
6 caseSensitive?: boolean;
7 id: string;
8 parentId?: string;
9 path?: string;
10}
11interface EntryRoute extends Route {
12 hasAction: boolean;
13 hasLoader: boolean;
14 hasClientAction: boolean;
15 hasClientLoader: boolean;
16 hasClientMiddleware: boolean;
17 hasErrorBoundary: boolean;
18 imports?: string[];
19 css?: string[];
20 module: string;
21 clientActionModule: string | undefined;
22 clientLoaderModule: string | undefined;
23 clientMiddlewareModule: string | undefined;
24 hydrateFallbackModule: string | undefined;
25 parentId?: string;
26}
27declare function createClientRoutesWithHMRRevalidationOptOut(needsRevalidation: Set<string>, manifest: RouteManifest<EntryRoute>, routeModulesCache: RouteModules, initialState: HydrationState, ssr: boolean, isSpaMode: boolean): DataRouteObject[];
28declare function createClientRoutes(manifest: RouteManifest<EntryRoute>, routeModulesCache: RouteModules, initialState: HydrationState | null, ssr: boolean, isSpaMode: boolean, parentId?: string, routesByParentId?: Record<string, Omit<EntryRoute, "children">[]>, needsRevalidation?: Set<string>): DataRouteObject[];
29declare function shouldHydrateRouteLoader(routeId: string, clientLoader: ClientLoaderFunction | undefined, hasLoader: boolean, isSpaMode: boolean): boolean;
30
31type SerializedError = {
32 message: string;
33 stack?: string;
34};
35interface FrameworkContextObject {
36 manifest: AssetsManifest;
37 routeModules: RouteModules;
38 criticalCss?: CriticalCss;
39 serverHandoffString?: string;
40 future: FutureConfig;
41 ssr: boolean;
42 isSpaMode: boolean;
43 routeDiscovery: ServerBuild["routeDiscovery"];
44 serializeError?(error: Error): SerializedError;
45 renderMeta?: {
46 didRenderScripts?: boolean;
47 streamCache?: Record<number, Promise<void> & {
48 result?: {
49 done: boolean;
50 value: string;
51 };
52 error?: unknown;
53 }>;
54 };
55}
56interface EntryContext extends FrameworkContextObject {
57 staticHandlerContext: StaticHandlerContext;
58 serverHandoffStream?: ReadableStream<Uint8Array>;
59}
60interface FutureConfig {
61 unstable_subResourceIntegrity: boolean;
62 unstable_trailingSlashAwareDataRequests: boolean;
63 v8_middleware: boolean;
64}
65type CriticalCss = string | {
66 rel: "stylesheet";
67 href: string;
68};
69interface AssetsManifest {
70 entry: {
71 imports: string[];
72 module: string;
73 };
74 routes: RouteManifest<EntryRoute>;
75 url: string;
76 version: string;
77 hmr?: {
78 timestamp?: number;
79 runtime: string;
80 };
81 sri?: Record<string, string> | true;
82}
83
84type ServerRouteManifest = RouteManifest<Omit<ServerRoute, "children">>;
85interface ServerRoute extends Route {
86 children: ServerRoute[];
87 module: ServerRouteModule;
88}
89
90type OptionalCriticalCss = CriticalCss | undefined;
91/**
92 * The output of the compiler for the server build.
93 */
94interface ServerBuild {
95 entry: {
96 module: ServerEntryModule;
97 };
98 routes: ServerRouteManifest;
99 assets: AssetsManifest;
100 basename?: string;
101 publicPath: string;
102 assetsBuildDirectory: string;
103 future: FutureConfig;
104 ssr: boolean;
105 unstable_getCriticalCss?: (args: {
106 pathname: string;
107 }) => OptionalCriticalCss | Promise<OptionalCriticalCss>;
108 /**
109 * @deprecated This is now done via a custom header during prerendering
110 */
111 isSpaMode: boolean;
112 prerender: string[];
113 routeDiscovery: {
114 mode: "lazy" | "initial";
115 manifestPath: string;
116 };
117 allowedActionOrigins?: string[] | false;
118}
119interface HandleDocumentRequestFunction {
120 (request: Request, responseStatusCode: number, responseHeaders: Headers, context: EntryContext, loadContext: MiddlewareEnabled extends true ? RouterContextProvider : AppLoadContext): Promise<Response> | Response;
121}
122interface HandleDataRequestFunction {
123 (response: Response, args: {
124 request: LoaderFunctionArgs["request"] | ActionFunctionArgs["request"];
125 context: LoaderFunctionArgs["context"] | ActionFunctionArgs["context"];
126 params: LoaderFunctionArgs["params"] | ActionFunctionArgs["params"];
127 }): Promise<Response> | Response;
128}
129interface HandleErrorFunction {
130 (error: unknown, args: {
131 request: LoaderFunctionArgs["request"] | ActionFunctionArgs["request"];
132 context: LoaderFunctionArgs["context"] | ActionFunctionArgs["context"];
133 params: LoaderFunctionArgs["params"] | ActionFunctionArgs["params"];
134 }): void;
135}
136/**
137 * A module that serves as the entry point for a Remix app during server
138 * rendering.
139 */
140interface ServerEntryModule {
141 default: HandleDocumentRequestFunction;
142 handleDataRequest?: HandleDataRequestFunction;
143 handleError?: HandleErrorFunction;
144 unstable_instrumentations?: unstable_ServerInstrumentation[];
145 streamTimeout?: number;
146}
147
148type ParamKeyValuePair = [string, string];
149type URLSearchParamsInit = string | ParamKeyValuePair[] | Record<string, string | string[]> | URLSearchParams;
150/**
151 Creates a URLSearchParams object using the given initializer.
152
153 This is identical to `new URLSearchParams(init)` except it also
154 supports arrays as values in the object form of the initializer
155 instead of just strings. This is convenient when you need multiple
156 values for a given key, but don't want to use an array initializer.
157
158 For example, instead of:
159
160 ```tsx
161 let searchParams = new URLSearchParams([
162 ['sort', 'name'],
163 ['sort', 'price']
164 ]);
165 ```
166 you can do:
167
168 ```
169 let searchParams = createSearchParams({
170 sort: ['name', 'price']
171 });
172 ```
173
174 @category Utils
175 */
176declare function createSearchParams(init?: URLSearchParamsInit): URLSearchParams;
177type JsonObject = {
178 [Key in string]: JsonValue;
179} & {
180 [Key in string]?: JsonValue | undefined;
181};
182type JsonArray = JsonValue[] | readonly JsonValue[];
183type JsonPrimitive = string | number | boolean | null;
184type JsonValue = JsonPrimitive | JsonObject | JsonArray;
185type SubmitTarget = HTMLFormElement | HTMLButtonElement | HTMLInputElement | FormData | URLSearchParams | JsonValue | null;
186/**
187 * Submit options shared by both navigations and fetchers
188 */
189interface SharedSubmitOptions {
190 /**
191 * The HTTP method used to submit the form. Overrides `<form method>`.
192 * Defaults to "GET".
193 */
194 method?: HTMLFormMethod;
195 /**
196 * The action URL path used to submit the form. Overrides `<form action>`.
197 * Defaults to the path of the current route.
198 */
199 action?: string;
200 /**
201 * The encoding used to submit the form. Overrides `<form encType>`.
202 * Defaults to "application/x-www-form-urlencoded".
203 */
204 encType?: FormEncType;
205 /**
206 * Determines whether the form action is relative to the route hierarchy or
207 * the pathname. Use this if you want to opt out of navigating the route
208 * hierarchy and want to instead route based on /-delimited URL segments
209 */
210 relative?: RelativeRoutingType;
211 /**
212 * In browser-based environments, prevent resetting scroll after this
213 * navigation when using the <ScrollRestoration> component
214 */
215 preventScrollReset?: boolean;
216 /**
217 * Enable flushSync for this submission's state updates
218 */
219 flushSync?: boolean;
220 /**
221 * Specify the default revalidation behavior after this submission
222 *
223 * If no `shouldRevalidate` functions are present on the active routes, then this
224 * value will be used directly. Otherwise it will be passed into `shouldRevalidate`
225 * so the route can make the final determination on revalidation. This can be
226 * useful when updating search params and you don't want to trigger a revalidation.
227 *
228 * By default (when not specified), loaders will revalidate according to the routers
229 * standard revalidation behavior.
230 */
231 unstable_defaultShouldRevalidate?: boolean;
232}
233/**
234 * Submit options available to fetchers
235 */
236interface FetcherSubmitOptions extends SharedSubmitOptions {
237}
238/**
239 * Submit options available to navigations
240 */
241interface SubmitOptions extends FetcherSubmitOptions {
242 /**
243 * Set `true` to replace the current entry in the browser's history stack
244 * instead of creating a new one (i.e. stay on "the same page"). Defaults
245 * to `false`.
246 */
247 replace?: boolean;
248 /**
249 * State object to add to the history stack entry for this navigation
250 */
251 state?: any;
252 /**
253 * Indicate a specific fetcherKey to use when using navigate=false
254 */
255 fetcherKey?: string;
256 /**
257 * navigate=false will use a fetcher instead of a navigation
258 */
259 navigate?: boolean;
260 /**
261 * Enable view transitions on this submission navigation
262 */
263 viewTransition?: boolean;
264}
265
266declare const FrameworkContext: React.Context<FrameworkContextObject | undefined>;
267/**
268 * Defines the [lazy route discovery](../../explanation/lazy-route-discovery)
269 * behavior of the link/form:
270 *
271 * - "render" - default, discover the route when the link renders
272 * - "none" - don't eagerly discover, only discover if the link is clicked
273 */
274type DiscoverBehavior = "render" | "none";
275/**
276 * Defines the prefetching behavior of the link:
277 *
278 * - "none": Never fetched
279 * - "intent": Fetched when the user focuses or hovers the link
280 * - "render": Fetched when the link is rendered
281 * - "viewport": Fetched when the link is in the viewport
282 */
283type PrefetchBehavior = "intent" | "render" | "none" | "viewport";
284/**
285 * Props for the {@link Links} component.
286 *
287 * @category Types
288 */
289interface LinksProps {
290 /**
291 * A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
292 * attribute to render on the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
293 * element
294 */
295 nonce?: string | undefined;
296}
297/**
298 * Renders all the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
299 * tags created by the route module's [`links`](../../start/framework/route-module#links)
300 * export. You should render it inside the [`<head>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head)
301 * of your document.
302 *
303 * @example
304 * import { Links } from "react-router";
305 *
306 * export default function Root() {
307 * return (
308 * <html>
309 * <head>
310 * <Links />
311 * </head>
312 * <body></body>
313 * </html>
314 * );
315 * }
316 *
317 * @public
318 * @category Components
319 * @mode framework
320 * @param props Props
321 * @param {LinksProps.nonce} props.nonce n/a
322 * @returns A collection of React elements for [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
323 * tags
324 */
325declare function Links({ nonce }: LinksProps): React.JSX.Element;
326/**
327 * Renders [`<link rel=prefetch|modulepreload>`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement/rel)
328 * tags for modules and data of another page to enable an instant navigation to
329 * that page. [`<Link prefetch>`](./Link#prefetch) uses this internally, but you
330 * can render it to prefetch a page for any other reason.
331 *
332 * For example, you may render one of this as the user types into a search field
333 * to prefetch search results before they click through to their selection.
334 *
335 * @example
336 * import { PrefetchPageLinks } from "react-router";
337 *
338 * <PrefetchPageLinks page="/absolute/path" />
339 *
340 * @public
341 * @category Components
342 * @mode framework
343 * @param props Props
344 * @param {PageLinkDescriptor.page} props.page n/a
345 * @param props.linkProps Additional props to spread onto the [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
346 * tags, such as [`crossOrigin`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement/crossOrigin),
347 * [`integrity`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement/integrity),
348 * [`rel`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement/rel),
349 * etc.
350 * @returns A collection of React elements for [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
351 * tags
352 */
353declare function PrefetchPageLinks({ page, ...linkProps }: PageLinkDescriptor): React.JSX.Element | null;
354/**
355 * Renders all the [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta)
356 * tags created by the route module's [`meta`](../../start/framework/route-module#meta)
357 * export. You should render it inside the [`<head>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head)
358 * of your document.
359 *
360 * @example
361 * import { Meta } from "react-router";
362 *
363 * export default function Root() {
364 * return (
365 * <html>
366 * <head>
367 * <Meta />
368 * </head>
369 * </html>
370 * );
371 * }
372 *
373 * @public
374 * @category Components
375 * @mode framework
376 * @returns A collection of React elements for [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta)
377 * tags
378 */
379declare function Meta(): React.JSX.Element;
380/**
381 * A couple common attributes:
382 *
383 * - `<Scripts crossOrigin>` for hosting your static assets on a different
384 * server than your app.
385 * - `<Scripts nonce>` to support a [content security policy for scripts](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src)
386 * with [nonce-sources](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/Sources#sources)
387 * for your [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)
388 * tags.
389 *
390 * You cannot pass through attributes such as [`async`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement/async),
391 * [`defer`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement/defer),
392 * [`noModule`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement/noModule),
393 * [`src`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement/src),
394 * or [`type`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement/type),
395 * because they are managed by React Router internally.
396 *
397 * @category Types
398 */
399type ScriptsProps = Omit<React.HTMLProps<HTMLScriptElement>, "async" | "children" | "dangerouslySetInnerHTML" | "defer" | "noModule" | "src" | "suppressHydrationWarning" | "type"> & {
400 /**
401 * A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
402 * attribute to render on the [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)
403 * element
404 */
405 nonce?: string | undefined;
406};
407/**
408 * Renders the client runtime of your app. It should be rendered inside the
409 * [`<body>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/body)
410 * of the document.
411 *
412 * If server rendering, you can omit `<Scripts/>` and the app will work as a
413 * traditional web app without JavaScript, relying solely on HTML and browser
414 * behaviors.
415 *
416 * @example
417 * import { Scripts } from "react-router";
418 *
419 * export default function Root() {
420 * return (
421 * <html>
422 * <head />
423 * <body>
424 * <Scripts />
425 * </body>
426 * </html>
427 * );
428 * }
429 *
430 * @public
431 * @category Components
432 * @mode framework
433 * @param scriptProps Additional props to spread onto the [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)
434 * tags, such as [`crossOrigin`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement/crossOrigin),
435 * [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce),
436 * etc.
437 * @returns A collection of React elements for [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)
438 * tags
439 */
440declare function Scripts(scriptProps: ScriptsProps): React.JSX.Element | null;
441
442/**
443 * @category Data Routers
444 */
445interface DOMRouterOpts {
446 /**
447 * Basename path for the application.
448 */
449 basename?: string;
450 /**
451 * A function that returns an {@link RouterContextProvider} instance
452 * which is provided as the `context` argument to client [`action`](../../start/data/route-object#action)s,
453 * [`loader`](../../start/data/route-object#loader)s and [middleware](../../how-to/middleware).
454 * This function is called to generate a fresh `context` instance on each
455 * navigation or fetcher call.
456 *
457 * ```tsx
458 * import {
459 * createContext,
460 * RouterContextProvider,
461 * } from "react-router";
462 *
463 * const apiClientContext = createContext<APIClient>();
464 *
465 * function createBrowserRouter(routes, {
466 * getContext() {
467 * let context = new RouterContextProvider();
468 * context.set(apiClientContext, getApiClient());
469 * return context;
470 * }
471 * })
472 * ```
473 */
474 getContext?: RouterInit["getContext"];
475 /**
476 * Future flags to enable for the router.
477 */
478 future?: Partial<FutureConfig$1>;
479 /**
480 * When Server-Rendering and opting-out of automatic hydration, the
481 * `hydrationData` option allows you to pass in hydration data from your
482 * server-render. This will almost always be a subset of data from the
483 * {@link StaticHandlerContext} value you get back from the {@link StaticHandler}'s
484 * `query` method:
485 *
486 * ```tsx
487 * const router = createBrowserRouter(routes, {
488 * hydrationData: {
489 * loaderData: {
490 * // [routeId]: serverLoaderData
491 * },
492 * // may also include `errors` and/or `actionData`
493 * },
494 * });
495 * ```
496 *
497 * **Partial Hydration Data**
498 *
499 * You will almost always include a complete set of `loaderData` to hydrate a
500 * server-rendered app. But in advanced use-cases (such as Framework Mode's
501 * [`clientLoader`](../../start/framework/route-module#clientLoader)), you may
502 * want to include `loaderData` for only some routes that were loaded/rendered
503 * on the server. This allows you to hydrate _some_ of the routes (such as the
504 * app layout/shell) while showing a `HydrateFallback` component and running
505 * the [`loader`](../../start/data/route-object#loader)s for other routes
506 * during hydration.
507 *
508 * A route [`loader`](../../start/data/route-object#loader) will run during
509 * hydration in two scenarios:
510 *
511 * 1. No hydration data is provided
512 * In these cases the `HydrateFallback` component will render on initial
513 * hydration
514 * 2. The `loader.hydrate` property is set to `true`
515 * This allows you to run the [`loader`](../../start/data/route-object#loader)
516 * even if you did not render a fallback on initial hydration (i.e., to
517 * prime a cache with hydration data)
518 *
519 * ```tsx
520 * const router = createBrowserRouter(
521 * [
522 * {
523 * id: "root",
524 * loader: rootLoader,
525 * Component: Root,
526 * children: [
527 * {
528 * id: "index",
529 * loader: indexLoader,
530 * HydrateFallback: IndexSkeleton,
531 * Component: Index,
532 * },
533 * ],
534 * },
535 * ],
536 * {
537 * hydrationData: {
538 * loaderData: {
539 * root: "ROOT DATA",
540 * // No index data provided
541 * },
542 * },
543 * }
544 * );
545 * ```
546 */
547 hydrationData?: HydrationState;
548 /**
549 * Array of instrumentation objects allowing you to instrument the router and
550 * individual routes prior to router initialization (and on any subsequently
551 * added routes via `route.lazy` or `patchRoutesOnNavigation`). This is
552 * mostly useful for observability such as wrapping navigations, fetches,
553 * as well as route loaders/actions/middlewares with logging and/or performance
554 * tracing. See the [docs](../../how-to/instrumentation) for more information.
555 *
556 * ```tsx
557 * let router = createBrowserRouter(routes, {
558 * unstable_instrumentations: [logging]
559 * });
560 *
561 *
562 * let logging = {
563 * router({ instrument }) {
564 * instrument({
565 * navigate: (impl, info) => logExecution(`navigate ${info.to}`, impl),
566 * fetch: (impl, info) => logExecution(`fetch ${info.to}`, impl)
567 * });
568 * },
569 * route({ instrument, id }) {
570 * instrument({
571 * middleware: (impl, info) => logExecution(
572 * `middleware ${info.request.url} (route ${id})`,
573 * impl
574 * ),
575 * loader: (impl, info) => logExecution(
576 * `loader ${info.request.url} (route ${id})`,
577 * impl
578 * ),
579 * action: (impl, info) => logExecution(
580 * `action ${info.request.url} (route ${id})`,
581 * impl
582 * ),
583 * })
584 * }
585 * };
586 *
587 * async function logExecution(label: string, impl: () => Promise<void>) {
588 * let start = performance.now();
589 * console.log(`start ${label}`);
590 * await impl();
591 * let duration = Math.round(performance.now() - start);
592 * console.log(`end ${label} (${duration}ms)`);
593 * }
594 * ```
595 */
596 unstable_instrumentations?: unstable_ClientInstrumentation[];
597 /**
598 * Override the default data strategy of running loaders in parallel -
599 * see the [docs](../../how-to/data-strategy) for more information.
600 *
601 * ```tsx
602 * let router = createBrowserRouter(routes, {
603 * async dataStrategy({
604 * matches,
605 * request,
606 * runClientMiddleware,
607 * }) {
608 * const matchesToLoad = matches.filter((m) =>
609 * m.shouldCallHandler(),
610 * );
611 *
612 * const results: Record<string, DataStrategyResult> = {};
613 * await runClientMiddleware(() =>
614 * Promise.all(
615 * matchesToLoad.map(async (match) => {
616 * results[match.route.id] = await match.resolve();
617 * }),
618 * ),
619 * );
620 * return results;
621 * },
622 * });
623 * ```
624 */
625 dataStrategy?: DataStrategyFunction;
626 /**
627 * Lazily define portions of the route tree on navigations.
628 * See {@link PatchRoutesOnNavigationFunction}.
629 *
630 * By default, React Router wants you to provide a full route tree up front via
631 * `createBrowserRouter(routes)`. This allows React Router to perform synchronous
632 * route matching, execute loaders, and then render route components in the most
633 * optimistic manner without introducing waterfalls. The tradeoff is that your
634 * initial JS bundle is larger by definition — which may slow down application
635 * start-up times as your application grows.
636 *
637 * To combat this, we introduced [`route.lazy`](../../start/data/route-object#lazy)
638 * in [v6.9.0](https://github.com/remix-run/react-router/blob/main/CHANGELOG.md#v690)
639 * which lets you lazily load the route _implementation_ ([`loader`](../../start/data/route-object#loader),
640 * [`Component`](../../start/data/route-object#Component), etc.) while still
641 * providing the route _definition_ aspects up front (`path`, `index`, etc.).
642 * This is a good middle ground. React Router still knows about your route
643 * definitions (the lightweight part) up front and can perform synchronous
644 * route matching, but then delay loading any of the route implementation
645 * aspects (the heavier part) until the route is actually navigated to.
646 *
647 * In some cases, even this doesn't go far enough. For huge applications,
648 * providing all route definitions up front can be prohibitively expensive.
649 * Additionally, it might not even be possible to provide all route definitions
650 * up front in certain Micro-Frontend or Module-Federation architectures.
651 *
652 * This is where `patchRoutesOnNavigation` comes in ([RFC](https://github.com/remix-run/react-router/discussions/11113)).
653 * This API is for advanced use-cases where you are unable to provide the full
654 * route tree up-front and need a way to lazily "discover" portions of the route
655 * tree at runtime. This feature is often referred to as ["Fog of War"](https://en.wikipedia.org/wiki/Fog_of_war),
656 * because similar to how video games expand the "world" as you move around -
657 * the router would be expanding its routing tree as the user navigated around
658 * the app - but would only ever end up loading portions of the tree that the
659 * user visited.
660 *
661 * `patchRoutesOnNavigation` will be called anytime React Router is unable to
662 * match a `path`. The arguments include the `path`, any partial `matches`,
663 * and a `patch` function you can call to patch new routes into the tree at a
664 * specific location. This method is executed during the `loading` portion of
665 * the navigation for `GET` requests and during the `submitting` portion of
666 * the navigation for non-`GET` requests.
667 *
668 * <details>
669 * <summary><b>Example <code>patchRoutesOnNavigation</code> Use Cases</b></summary>
670 *
671 * **Patching children into an existing route**
672 *
673 * ```tsx
674 * const router = createBrowserRouter(
675 * [
676 * {
677 * id: "root",
678 * path: "/",
679 * Component: RootComponent,
680 * },
681 * ],
682 * {
683 * async patchRoutesOnNavigation({ patch, path }) {
684 * if (path === "/a") {
685 * // Load/patch the `a` route as a child of the route with id `root`
686 * let route = await getARoute();
687 * // ^ { path: 'a', Component: A }
688 * patch("root", [route]);
689 * }
690 * },
691 * }
692 * );
693 * ```
694 *
695 * In the above example, if the user clicks a link to `/a`, React Router
696 * won't match any routes initially and will call `patchRoutesOnNavigation`
697 * with a `path = "/a"` and a `matches` array containing the root route
698 * match. By calling `patch('root', [route])`, the new route will be added
699 * to the route tree as a child of the `root` route and React Router will
700 * perform matching on the updated routes. This time it will successfully
701 * match the `/a` path and the navigation will complete successfully.
702 *
703 * **Patching new root-level routes**
704 *
705 * If you need to patch a new route to the top of the tree (i.e., it doesn't
706 * have a parent), you can pass `null` as the `routeId`:
707 *
708 * ```tsx
709 * const router = createBrowserRouter(
710 * [
711 * {
712 * id: "root",
713 * path: "/",
714 * Component: RootComponent,
715 * },
716 * ],
717 * {
718 * async patchRoutesOnNavigation({ patch, path }) {
719 * if (path === "/root-sibling") {
720 * // Load/patch the `/root-sibling` route as a sibling of the root route
721 * let route = await getRootSiblingRoute();
722 * // ^ { path: '/root-sibling', Component: RootSibling }
723 * patch(null, [route]);
724 * }
725 * },
726 * }
727 * );
728 * ```
729 *
730 * **Patching subtrees asynchronously**
731 *
732 * You can also perform asynchronous matching to lazily fetch entire sections
733 * of your application:
734 *
735 * ```tsx
736 * let router = createBrowserRouter(
737 * [
738 * {
739 * path: "/",
740 * Component: Home,
741 * },
742 * ],
743 * {
744 * async patchRoutesOnNavigation({ patch, path }) {
745 * if (path.startsWith("/dashboard")) {
746 * let children = await import("./dashboard");
747 * patch(null, children);
748 * }
749 * if (path.startsWith("/account")) {
750 * let children = await import("./account");
751 * patch(null, children);
752 * }
753 * },
754 * }
755 * );
756 * ```
757 *
758 * <docs-info>If in-progress execution of `patchRoutesOnNavigation` is
759 * interrupted by a later navigation, then any remaining `patch` calls in
760 * the interrupted execution will not update the route tree because the
761 * operation was cancelled.</docs-info>
762 *
763 * **Co-locating route discovery with route definition**
764 *
765 * If you don't wish to perform your own pseudo-matching, you can leverage
766 * the partial `matches` array and the [`handle`](../../start/data/route-object#handle)
767 * field on a route to keep the children definitions co-located:
768 *
769 * ```tsx
770 * let router = createBrowserRouter(
771 * [
772 * {
773 * path: "/",
774 * Component: Home,
775 * },
776 * {
777 * path: "/dashboard",
778 * children: [
779 * {
780 * // If we want to include /dashboard in the critical routes, we need to
781 * // also include it's index route since patchRoutesOnNavigation will not be
782 * // called on a navigation to `/dashboard` because it will have successfully
783 * // matched the `/dashboard` parent route
784 * index: true,
785 * // ...
786 * },
787 * ],
788 * handle: {
789 * lazyChildren: () => import("./dashboard"),
790 * },
791 * },
792 * {
793 * path: "/account",
794 * children: [
795 * {
796 * index: true,
797 * // ...
798 * },
799 * ],
800 * handle: {
801 * lazyChildren: () => import("./account"),
802 * },
803 * },
804 * ],
805 * {
806 * async patchRoutesOnNavigation({ matches, patch }) {
807 * let leafRoute = matches[matches.length - 1]?.route;
808 * if (leafRoute?.handle?.lazyChildren) {
809 * let children =
810 * await leafRoute.handle.lazyChildren();
811 * patch(leafRoute.id, children);
812 * }
813 * },
814 * }
815 * );
816 * ```
817 *
818 * **A note on routes with parameters**
819 *
820 * Because React Router uses ranked routes to find the best match for a
821 * given path, there is an interesting ambiguity introduced when only a
822 * partial route tree is known at any given point in time. If we match a
823 * fully static route such as `path: "/about/contact-us"` then we know we've
824 * found the right match since it's composed entirely of static URL segments.
825 * Thus, we do not need to bother asking for any other potentially
826 * higher-scoring routes.
827 *
828 * However, routes with parameters (dynamic or splat) can't make this
829 * assumption because there might be a not-yet-discovered route that scores
830 * higher. Consider a full route tree such as:
831 *
832 * ```tsx
833 * // Assume this is the full route tree for your app
834 * const routes = [
835 * {
836 * path: "/",
837 * Component: Home,
838 * },
839 * {
840 * id: "blog",
841 * path: "/blog",
842 * Component: BlogLayout,
843 * children: [
844 * { path: "new", Component: NewPost },
845 * { path: ":slug", Component: BlogPost },
846 * ],
847 * },
848 * ];
849 * ```
850 *
851 * And then assume we want to use `patchRoutesOnNavigation` to fill this in
852 * as the user navigates around:
853 *
854 * ```tsx
855 * // Start with only the index route
856 * const router = createBrowserRouter(
857 * [
858 * {
859 * path: "/",
860 * Component: Home,
861 * },
862 * ],
863 * {
864 * async patchRoutesOnNavigation({ patch, path }) {
865 * if (path === "/blog/new") {
866 * patch("blog", [
867 * {
868 * path: "new",
869 * Component: NewPost,
870 * },
871 * ]);
872 * } else if (path.startsWith("/blog")) {
873 * patch("blog", [
874 * {
875 * path: ":slug",
876 * Component: BlogPost,
877 * },
878 * ]);
879 * }
880 * },
881 * }
882 * );
883 * ```
884 *
885 * If the user were to a blog post first (i.e., `/blog/my-post`) we would
886 * patch in the `:slug` route. Then, if the user navigated to `/blog/new` to
887 * write a new post, we'd match `/blog/:slug` but it wouldn't be the _right_
888 * match! We need to call `patchRoutesOnNavigation` just in case there
889 * exists a higher-scoring route we've not yet discovered, which in this
890 * case there is.
891 *
892 * So, anytime React Router matches a path that contains at least one param,
893 * it will call `patchRoutesOnNavigation` and match routes again just to
894 * confirm it has found the best match.
895 *
896 * If your `patchRoutesOnNavigation` implementation is expensive or making
897 * side effect [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/fetch)
898 * calls to a backend server, you may want to consider tracking previously
899 * seen routes to avoid over-fetching in cases where you know the proper
900 * route has already been found. This can usually be as simple as
901 * maintaining a small cache of prior `path` values for which you've already
902 * patched in the right routes:
903 *
904 * ```tsx
905 * let discoveredRoutes = new Set();
906 *
907 * const router = createBrowserRouter(routes, {
908 * async patchRoutesOnNavigation({ patch, path }) {
909 * if (discoveredRoutes.has(path)) {
910 * // We've seen this before so nothing to patch in and we can let the router
911 * // use the routes it already knows about
912 * return;
913 * }
914 *
915 * discoveredRoutes.add(path);
916 *
917 * // ... patch routes in accordingly
918 * },
919 * });
920 * ```
921 * </details>
922 */
923 patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;
924 /**
925 * [`Window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) object
926 * override. Defaults to the global `window` instance.
927 */
928 window?: Window;
929}
930/**
931 * Create a new {@link DataRouter| data router} that manages the application
932 * path via [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
933 * and [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState).
934 *
935 * @public
936 * @category Data Routers
937 * @mode data
938 * @param routes Application routes
939 * @param opts Options
940 * @param {DOMRouterOpts.basename} opts.basename n/a
941 * @param {DOMRouterOpts.dataStrategy} opts.dataStrategy n/a
942 * @param {DOMRouterOpts.future} opts.future n/a
943 * @param {DOMRouterOpts.getContext} opts.getContext n/a
944 * @param {DOMRouterOpts.hydrationData} opts.hydrationData n/a
945 * @param {DOMRouterOpts.unstable_instrumentations} opts.unstable_instrumentations n/a
946 * @param {DOMRouterOpts.patchRoutesOnNavigation} opts.patchRoutesOnNavigation n/a
947 * @param {DOMRouterOpts.window} opts.window n/a
948 * @returns An initialized {@link DataRouter| data router} to pass to {@link RouterProvider | `<RouterProvider>`}
949 */
950declare function createBrowserRouter(routes: RouteObject[], opts?: DOMRouterOpts): Router;
951/**
952 * Create a new {@link DataRouter| data router} that manages the application
953 * path via the URL [`hash`](https://developer.mozilla.org/en-US/docs/Web/API/URL/hash).
954 *
955 * @public
956 * @category Data Routers
957 * @mode data
958 * @param routes Application routes
959 * @param opts Options
960 * @param {DOMRouterOpts.basename} opts.basename n/a
961 * @param {DOMRouterOpts.future} opts.future n/a
962 * @param {DOMRouterOpts.getContext} opts.getContext n/a
963 * @param {DOMRouterOpts.hydrationData} opts.hydrationData n/a
964 * @param {DOMRouterOpts.unstable_instrumentations} opts.unstable_instrumentations n/a
965 * @param {DOMRouterOpts.dataStrategy} opts.dataStrategy n/a
966 * @param {DOMRouterOpts.patchRoutesOnNavigation} opts.patchRoutesOnNavigation n/a
967 * @param {DOMRouterOpts.window} opts.window n/a
968 * @returns An initialized {@link DataRouter| data router} to pass to {@link RouterProvider | `<RouterProvider>`}
969 */
970declare function createHashRouter(routes: RouteObject[], opts?: DOMRouterOpts): Router;
971/**
972 * @category Types
973 */
974interface BrowserRouterProps {
975 /**
976 * Application basename
977 */
978 basename?: string;
979 /**
980 * {@link Route | `<Route>`} components describing your route configuration
981 */
982 children?: React.ReactNode;
983 /**
984 * Control whether router state updates are internally wrapped in
985 * [`React.startTransition`](https://react.dev/reference/react/startTransition).
986 *
987 * - When left `undefined`, all router state updates are wrapped in
988 * `React.startTransition`
989 * - When set to `true`, {@link Link} and {@link Form} navigations will be wrapped
990 * in `React.startTransition` and all router state updates are wrapped in
991 * `React.startTransition`
992 * - When set to `false`, the router will not leverage `React.startTransition`
993 * on any navigations or state changes.
994 *
995 * For more information, please see the [docs](https://reactrouter.com/explanation/react-transitions).
996 */
997 unstable_useTransitions?: boolean;
998 /**
999 * [`Window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) object
1000 * override. Defaults to the global `window` instance
1001 */
1002 window?: Window;
1003}
1004/**
1005 * A declarative {@link Router | `<Router>`} using the browser [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
1006 * API for client-side routing.
1007 *
1008 * @public
1009 * @category Declarative Routers
1010 * @mode declarative
1011 * @param props Props
1012 * @param {BrowserRouterProps.basename} props.basename n/a
1013 * @param {BrowserRouterProps.children} props.children n/a
1014 * @param {BrowserRouterProps.unstable_useTransitions} props.unstable_useTransitions n/a
1015 * @param {BrowserRouterProps.window} props.window n/a
1016 * @returns A declarative {@link Router | `<Router>`} using the browser [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
1017 * API for client-side routing.
1018 */
1019declare function BrowserRouter({ basename, children, unstable_useTransitions, window, }: BrowserRouterProps): React.JSX.Element;
1020/**
1021 * @category Types
1022 */
1023interface HashRouterProps {
1024 /**
1025 * Application basename
1026 */
1027 basename?: string;
1028 /**
1029 * {@link Route | `<Route>`} components describing your route configuration
1030 */
1031 children?: React.ReactNode;
1032 /**
1033 * Control whether router state updates are internally wrapped in
1034 * [`React.startTransition`](https://react.dev/reference/react/startTransition).
1035 *
1036 * - When left `undefined`, all router state updates are wrapped in
1037 * `React.startTransition`
1038 * - When set to `true`, {@link Link} and {@link Form} navigations will be wrapped
1039 * in `React.startTransition` and all router state updates are wrapped in
1040 * `React.startTransition`
1041 * - When set to `false`, the router will not leverage `React.startTransition`
1042 * on any navigations or state changes.
1043 *
1044 * For more information, please see the [docs](https://reactrouter.com/explanation/react-transitions).
1045 */
1046 unstable_useTransitions?: boolean;
1047 /**
1048 * [`Window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) object
1049 * override. Defaults to the global `window` instance
1050 */
1051 window?: Window;
1052}
1053/**
1054 * A declarative {@link Router | `<Router>`} that stores the location in the
1055 * [`hash`](https://developer.mozilla.org/en-US/docs/Web/API/URL/hash) portion
1056 * of the URL so it is not sent to the server.
1057 *
1058 * @public
1059 * @category Declarative Routers
1060 * @mode declarative
1061 * @param props Props
1062 * @param {HashRouterProps.basename} props.basename n/a
1063 * @param {HashRouterProps.children} props.children n/a
1064 * @param {HashRouterProps.unstable_useTransitions} props.unstable_useTransitions n/a
1065 * @param {HashRouterProps.window} props.window n/a
1066 * @returns A declarative {@link Router | `<Router>`} using the URL [`hash`](https://developer.mozilla.org/en-US/docs/Web/API/URL/hash)
1067 * for client-side routing.
1068 */
1069declare function HashRouter({ basename, children, unstable_useTransitions, window, }: HashRouterProps): React.JSX.Element;
1070/**
1071 * @category Types
1072 */
1073interface HistoryRouterProps {
1074 /**
1075 * Application basename
1076 */
1077 basename?: string;
1078 /**
1079 * {@link Route | `<Route>`} components describing your route configuration
1080 */
1081 children?: React.ReactNode;
1082 /**
1083 * A {@link History} implementation for use by the router
1084 */
1085 history: History;
1086 /**
1087 * Control whether router state updates are internally wrapped in
1088 * [`React.startTransition`](https://react.dev/reference/react/startTransition).
1089 *
1090 * - When left `undefined`, all router state updates are wrapped in
1091 * `React.startTransition`
1092 * - When set to `true`, {@link Link} and {@link Form} navigations will be wrapped
1093 * in `React.startTransition` and all router state updates are wrapped in
1094 * `React.startTransition`
1095 * - When set to `false`, the router will not leverage `React.startTransition`
1096 * on any navigations or state changes.
1097 *
1098 * For more information, please see the [docs](https://reactrouter.com/explanation/react-transitions).
1099 */
1100 unstable_useTransitions?: boolean;
1101}
1102/**
1103 * A declarative {@link Router | `<Router>`} that accepts a pre-instantiated
1104 * `history` object.
1105 * It's important to note that using your own `history` object is highly discouraged
1106 * and may add two versions of the `history` library to your bundles unless you use
1107 * the same version of the `history` library that React Router uses internally.
1108 *
1109 * @name unstable_HistoryRouter
1110 * @public
1111 * @category Declarative Routers
1112 * @mode declarative
1113 * @param props Props
1114 * @param {HistoryRouterProps.basename} props.basename n/a
1115 * @param {HistoryRouterProps.children} props.children n/a
1116 * @param {HistoryRouterProps.history} props.history n/a
1117 * @param {HistoryRouterProps.unstable_useTransitions} props.unstable_useTransitions n/a
1118 * @returns A declarative {@link Router | `<Router>`} using the provided history
1119 * implementation for client-side routing.
1120 */
1121declare function HistoryRouter({ basename, children, history, unstable_useTransitions, }: HistoryRouterProps): React.JSX.Element;
1122declare namespace HistoryRouter {
1123 var displayName: string;
1124}
1125/**
1126 * @category Types
1127 */
1128interface LinkProps extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href"> {
1129 /**
1130 * Defines the link [lazy route discovery](../../explanation/lazy-route-discovery) behavior.
1131 *
1132 * - **render** — default, discover the route when the link renders
1133 * - **none** — don't eagerly discover, only discover if the link is clicked
1134 *
1135 * ```tsx
1136 * <Link /> // default ("render")
1137 * <Link discover="render" />
1138 * <Link discover="none" />
1139 * ```
1140 */
1141 discover?: DiscoverBehavior;
1142 /**
1143 * Defines the data and module prefetching behavior for the link.
1144 *
1145 * ```tsx
1146 * <Link /> // default
1147 * <Link prefetch="none" />
1148 * <Link prefetch="intent" />
1149 * <Link prefetch="render" />
1150 * <Link prefetch="viewport" />
1151 * ```
1152 *
1153 * - **none** — default, no prefetching
1154 * - **intent** — prefetches when the user hovers or focuses the link
1155 * - **render** — prefetches when the link renders
1156 * - **viewport** — prefetches when the link is in the viewport, very useful for mobile
1157 *
1158 * Prefetching is done with HTML [`<link rel="prefetch">`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
1159 * tags. They are inserted after the link.
1160 *
1161 * ```tsx
1162 * <a href="..." />
1163 * <a href="..." />
1164 * <link rel="prefetch" /> // might conditionally render
1165 * ```
1166 *
1167 * Because of this, if you are using `nav :last-child` you will need to use
1168 * `nav :last-of-type` so the styles don't conditionally fall off your last link
1169 * (and any other similar selectors).
1170 */
1171 prefetch?: PrefetchBehavior;
1172 /**
1173 * Will use document navigation instead of client side routing when the link is
1174 * clicked: the browser will handle the transition normally (as if it were an
1175 * [`<a href>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a)).
1176 *
1177 * ```tsx
1178 * <Link to="/logout" reloadDocument />
1179 * ```
1180 */
1181 reloadDocument?: boolean;
1182 /**
1183 * Replaces the current entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
1184 * stack instead of pushing a new one onto it.
1185 *
1186 * ```tsx
1187 * <Link replace />
1188 * ```
1189 *
1190 * ```
1191 * # with a history stack like this
1192 * A -> B
1193 *
1194 * # normal link click pushes a new entry
1195 * A -> B -> C
1196 *
1197 * # but with `replace`, B is replaced by C
1198 * A -> C
1199 * ```
1200 */
1201 replace?: boolean;
1202 /**
1203 * Adds persistent client side routing state to the next location.
1204 *
1205 * ```tsx
1206 * <Link to="/somewhere/else" state={{ some: "value" }} />
1207 * ```
1208 *
1209 * The location state is accessed from the `location`.
1210 *
1211 * ```tsx
1212 * function SomeComp() {
1213 * const location = useLocation();
1214 * location.state; // { some: "value" }
1215 * }
1216 * ```
1217 *
1218 * This state is inaccessible on the server as it is implemented on top of
1219 * [`history.state`](https://developer.mozilla.org/en-US/docs/Web/API/History/state)
1220 */
1221 state?: any;
1222 /**
1223 * Prevents the scroll position from being reset to the top of the window when
1224 * the link is clicked and the app is using {@link ScrollRestoration}. This only
1225 * prevents new locations resetting scroll to the top, scroll position will be
1226 * restored for back/forward button navigation.
1227 *
1228 * ```tsx
1229 * <Link to="?tab=one" preventScrollReset />
1230 * ```
1231 */
1232 preventScrollReset?: boolean;
1233 /**
1234 * Defines the relative path behavior for the link.
1235 *
1236 * ```tsx
1237 * <Link to=".." /> // default: "route"
1238 * <Link relative="route" />
1239 * <Link relative="path" />
1240 * ```
1241 *
1242 * Consider a route hierarchy where a parent route pattern is `"blog"` and a child
1243 * route pattern is `"blog/:slug/edit"`.
1244 *
1245 * - **route** — default, resolves the link relative to the route pattern. In the
1246 * example above, a relative link of `"..."` will remove both `:slug/edit` segments
1247 * back to `"/blog"`.
1248 * - **path** — relative to the path so `"..."` will only remove one URL segment up
1249 * to `"/blog/:slug"`
1250 *
1251 * Note that index routes and layout routes do not have paths so they are not
1252 * included in the relative path calculation.
1253 */
1254 relative?: RelativeRoutingType;
1255 /**
1256 * Can be a string or a partial {@link Path}:
1257 *
1258 * ```tsx
1259 * <Link to="/some/path" />
1260 *
1261 * <Link
1262 * to={{
1263 * pathname: "/some/path",
1264 * search: "?query=string",
1265 * hash: "#hash",
1266 * }}
1267 * />
1268 * ```
1269 */
1270 to: To;
1271 /**
1272 * Enables a [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API)
1273 * for this navigation.
1274 *
1275 * ```jsx
1276 * <Link to={to} viewTransition>
1277 * Click me
1278 * </Link>
1279 * ```
1280 *
1281 * To apply specific styles for the transition, see {@link useViewTransitionState}
1282 */
1283 viewTransition?: boolean;
1284 /**
1285 * Specify the default revalidation behavior for the navigation.
1286 *
1287 * ```tsx
1288 * <Link to="/some/path" unstable_defaultShouldRevalidate={false} />
1289 * ```
1290 *
1291 * If no `shouldRevalidate` functions are present on the active routes, then this
1292 * value will be used directly. Otherwise it will be passed into `shouldRevalidate`
1293 * so the route can make the final determination on revalidation. This can be
1294 * useful when updating search params and you don't want to trigger a revalidation.
1295 *
1296 * By default (when not specified), loaders will revalidate according to the routers
1297 * standard revalidation behavior.
1298 */
1299 unstable_defaultShouldRevalidate?: boolean;
1300}
1301/**
1302 * A progressively enhanced [`<a href>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a)
1303 * wrapper to enable navigation with client-side routing.
1304 *
1305 * @example
1306 * import { Link } from "react-router";
1307 *
1308 * <Link to="/dashboard">Dashboard</Link>;
1309 *
1310 * <Link
1311 * to={{
1312 * pathname: "/some/path",
1313 * search: "?query=string",
1314 * hash: "#hash",
1315 * }}
1316 * />;
1317 *
1318 * @public
1319 * @category Components
1320 * @param {LinkProps.discover} props.discover [modes: framework] n/a
1321 * @param {LinkProps.prefetch} props.prefetch [modes: framework] n/a
1322 * @param {LinkProps.preventScrollReset} props.preventScrollReset [modes: framework, data] n/a
1323 * @param {LinkProps.relative} props.relative n/a
1324 * @param {LinkProps.reloadDocument} props.reloadDocument n/a
1325 * @param {LinkProps.replace} props.replace n/a
1326 * @param {LinkProps.state} props.state n/a
1327 * @param {LinkProps.to} props.to n/a
1328 * @param {LinkProps.viewTransition} props.viewTransition [modes: framework, data] n/a
1329 * @param {LinkProps.unstable_defaultShouldRevalidate} props.unstable_defaultShouldRevalidate n/a
1330 */
1331declare const Link: React.ForwardRefExoticComponent<LinkProps & React.RefAttributes<HTMLAnchorElement>>;
1332/**
1333 * The object passed to {@link NavLink} `children`, `className`, and `style` prop
1334 * callbacks to render and style the link based on its state.
1335 *
1336 * ```
1337 * // className
1338 * <NavLink
1339 * to="/messages"
1340 * className={({ isActive, isPending }) =>
1341 * isPending ? "pending" : isActive ? "active" : ""
1342 * }
1343 * >
1344 * Messages
1345 * </NavLink>
1346 *
1347 * // style
1348 * <NavLink
1349 * to="/messages"
1350 * style={({ isActive, isPending }) => {
1351 * return {
1352 * fontWeight: isActive ? "bold" : "",
1353 * color: isPending ? "red" : "black",
1354 * }
1355 * )}
1356 * />
1357 *
1358 * // children
1359 * <NavLink to="/tasks">
1360 * {({ isActive, isPending }) => (
1361 * <span className={isActive ? "active" : ""}>Tasks</span>
1362 * )}
1363 * </NavLink>
1364 * ```
1365 *
1366 */
1367type NavLinkRenderProps = {
1368 /**
1369 * Indicates if the link's URL matches the current {@link Location}.
1370 */
1371 isActive: boolean;
1372 /**
1373 * Indicates if the pending {@link Location} matches the link's URL. Only
1374 * available in Framework/Data modes.
1375 */
1376 isPending: boolean;
1377 /**
1378 * Indicates if a view transition to the link's URL is in progress.
1379 * See {@link useViewTransitionState}
1380 */
1381 isTransitioning: boolean;
1382};
1383/**
1384 * @category Types
1385 */
1386interface NavLinkProps extends Omit<LinkProps, "className" | "style" | "children"> {
1387 /**
1388 * Can be regular React children or a function that receives an object with the
1389 * `active` and `pending` states of the link.
1390 *
1391 * ```tsx
1392 * <NavLink to="/tasks">
1393 * {({ isActive }) => (
1394 * <span className={isActive ? "active" : ""}>Tasks</span>
1395 * )}
1396 * </NavLink>
1397 * ```
1398 */
1399 children?: React.ReactNode | ((props: NavLinkRenderProps) => React.ReactNode);
1400 /**
1401 * Changes the matching logic to make it case-sensitive:
1402 *
1403 * | Link | URL | isActive |
1404 * | -------------------------------------------- | ------------- | -------- |
1405 * | `<NavLink to="/SpOnGe-bOB" />` | `/sponge-bob` | true |
1406 * | `<NavLink to="/SpOnGe-bOB" caseSensitive />` | `/sponge-bob` | false |
1407 */
1408 caseSensitive?: boolean;
1409 /**
1410 * Classes are automatically applied to `NavLink` that correspond to the state.
1411 *
1412 * ```css
1413 * a.active {
1414 * color: red;
1415 * }
1416 * a.pending {
1417 * color: blue;
1418 * }
1419 * a.transitioning {
1420 * view-transition-name: my-transition;
1421 * }
1422 * ```
1423 *
1424 * Or you can specify a function that receives {@link NavLinkRenderProps} and
1425 * returns the `className`:
1426 *
1427 * ```tsx
1428 * <NavLink className={({ isActive, isPending }) => (
1429 * isActive ? "my-active-class" :
1430 * isPending ? "my-pending-class" :
1431 * ""
1432 * )} />
1433 * ```
1434 */
1435 className?: string | ((props: NavLinkRenderProps) => string | undefined);
1436 /**
1437 * Changes the matching logic for the `active` and `pending` states to only match
1438 * to the "end" of the {@link NavLinkProps.to}. If the URL is longer, it will no
1439 * longer be considered active.
1440 *
1441 * | Link | URL | isActive |
1442 * | ----------------------------- | ------------ | -------- |
1443 * | `<NavLink to="/tasks" />` | `/tasks` | true |
1444 * | `<NavLink to="/tasks" />` | `/tasks/123` | true |
1445 * | `<NavLink to="/tasks" end />` | `/tasks` | true |
1446 * | `<NavLink to="/tasks" end />` | `/tasks/123` | false |
1447 *
1448 * `<NavLink to="/">` is an exceptional case because _every_ URL matches `/`.
1449 * To avoid this matching every single route by default, it effectively ignores
1450 * the `end` prop and only matches when you're at the root route.
1451 */
1452 end?: boolean;
1453 /**
1454 * Styles can also be applied dynamically via a function that receives
1455 * {@link NavLinkRenderProps} and returns the styles:
1456 *
1457 * ```tsx
1458 * <NavLink to="/tasks" style={{ color: "red" }} />
1459 * <NavLink to="/tasks" style={({ isActive, isPending }) => ({
1460 * color:
1461 * isActive ? "red" :
1462 * isPending ? "blue" : "black"
1463 * })} />
1464 * ```
1465 */
1466 style?: React.CSSProperties | ((props: NavLinkRenderProps) => React.CSSProperties | undefined);
1467}
1468/**
1469 * Wraps {@link Link | `<Link>`} with additional props for styling active and
1470 * pending states.
1471 *
1472 * - Automatically applies classes to the link based on its `active` and `pending`
1473 * states, see {@link NavLinkProps.className}
1474 * - Note that `pending` is only available with Framework and Data modes.
1475 * - Automatically applies `aria-current="page"` to the link when the link is active.
1476 * See [`aria-current`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-current)
1477 * on MDN.
1478 * - States are additionally available through the className, style, and children
1479 * render props. See {@link NavLinkRenderProps}.
1480 *
1481 * @example
1482 * <NavLink to="/message">Messages</NavLink>
1483 *
1484 * // Using render props
1485 * <NavLink
1486 * to="/messages"
1487 * className={({ isActive, isPending }) =>
1488 * isPending ? "pending" : isActive ? "active" : ""
1489 * }
1490 * >
1491 * Messages
1492 * </NavLink>
1493 *
1494 * @public
1495 * @category Components
1496 * @param {NavLinkProps.caseSensitive} props.caseSensitive n/a
1497 * @param {NavLinkProps.children} props.children n/a
1498 * @param {NavLinkProps.className} props.className n/a
1499 * @param {NavLinkProps.discover} props.discover [modes: framework] n/a
1500 * @param {NavLinkProps.end} props.end n/a
1501 * @param {NavLinkProps.prefetch} props.prefetch [modes: framework] n/a
1502 * @param {NavLinkProps.preventScrollReset} props.preventScrollReset [modes: framework, data] n/a
1503 * @param {NavLinkProps.relative} props.relative n/a
1504 * @param {NavLinkProps.reloadDocument} props.reloadDocument n/a
1505 * @param {NavLinkProps.replace} props.replace n/a
1506 * @param {NavLinkProps.state} props.state n/a
1507 * @param {NavLinkProps.style} props.style n/a
1508 * @param {NavLinkProps.to} props.to n/a
1509 * @param {NavLinkProps.viewTransition} props.viewTransition [modes: framework, data] n/a
1510 */
1511declare const NavLink: React.ForwardRefExoticComponent<NavLinkProps & React.RefAttributes<HTMLAnchorElement>>;
1512/**
1513 * Form props shared by navigations and fetchers
1514 */
1515interface SharedFormProps extends React.FormHTMLAttributes<HTMLFormElement> {
1516 /**
1517 * The HTTP verb to use when the form is submitted. Supports `"delete"`,
1518 * `"get"`, `"patch"`, `"post"`, and `"put"`.
1519 *
1520 * Native [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form)
1521 * only supports `"get"` and `"post"`, avoid the other verbs if you'd like to
1522 * support progressive enhancement
1523 */
1524 method?: HTMLFormMethod;
1525 /**
1526 * The encoding type to use for the form submission.
1527 *
1528 * ```tsx
1529 * <Form encType="application/x-www-form-urlencoded"/> // Default
1530 * <Form encType="multipart/form-data"/>
1531 * <Form encType="text/plain"/>
1532 * ```
1533 */
1534 encType?: "application/x-www-form-urlencoded" | "multipart/form-data" | "text/plain";
1535 /**
1536 * The URL to submit the form data to. If `undefined`, this defaults to the
1537 * closest route in context.
1538 */
1539 action?: string;
1540 /**
1541 * Determines whether the form action is relative to the route hierarchy or
1542 * the pathname. Use this if you want to opt out of navigating the route
1543 * hierarchy and want to instead route based on slash-delimited URL segments.
1544 * See {@link RelativeRoutingType}.
1545 */
1546 relative?: RelativeRoutingType;
1547 /**
1548 * Prevent the scroll position from resetting to the top of the viewport on
1549 * completion of the navigation when using the
1550 * {@link ScrollRestoration | `<ScrollRestoration>`} component
1551 */
1552 preventScrollReset?: boolean;
1553 /**
1554 * A function to call when the form is submitted. If you call
1555 * [`event.preventDefault()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
1556 * then this form will not do anything.
1557 */
1558 onSubmit?: React.FormEventHandler<HTMLFormElement>;
1559 /**
1560 * Specify the default revalidation behavior after this submission
1561 *
1562 * If no `shouldRevalidate` functions are present on the active routes, then this
1563 * value will be used directly. Otherwise it will be passed into `shouldRevalidate`
1564 * so the route can make the final determination on revalidation. This can be
1565 * useful when updating search params and you don't want to trigger a revalidation.
1566 *
1567 * By default (when not specified), loaders will revalidate according to the routers
1568 * standard revalidation behavior.
1569 */
1570 unstable_defaultShouldRevalidate?: boolean;
1571}
1572/**
1573 * Form props available to fetchers
1574 * @category Types
1575 */
1576interface FetcherFormProps extends SharedFormProps {
1577}
1578/**
1579 * Form props available to navigations
1580 * @category Types
1581 */
1582interface FormProps extends SharedFormProps {
1583 /**
1584 * Defines the form [lazy route discovery](../../explanation/lazy-route-discovery) behavior.
1585 *
1586 * - **render** — default, discover the route when the form renders
1587 * - **none** — don't eagerly discover, only discover if the form is submitted
1588 *
1589 * ```tsx
1590 * <Form /> // default ("render")
1591 * <Form discover="render" />
1592 * <Form discover="none" />
1593 * ```
1594 */
1595 discover?: DiscoverBehavior;
1596 /**
1597 * Indicates a specific fetcherKey to use when using `navigate={false}` so you
1598 * can pick up the fetcher's state in a different component in a {@link useFetcher}.
1599 */
1600 fetcherKey?: string;
1601 /**
1602 * When `false`, skips the navigation and submits via a fetcher internally.
1603 * This is essentially a shorthand for {@link useFetcher} + `<fetcher.Form>` where
1604 * you don't care about the resulting data in this component.
1605 */
1606 navigate?: boolean;
1607 /**
1608 * Forces a full document navigation instead of client side routing and data
1609 * fetch.
1610 */
1611 reloadDocument?: boolean;
1612 /**
1613 * Replaces the current entry in the browser [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
1614 * stack when the form navigates. Use this if you don't want the user to be
1615 * able to click "back" to the page with the form on it.
1616 */
1617 replace?: boolean;
1618 /**
1619 * State object to add to the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
1620 * stack entry for this navigation
1621 */
1622 state?: any;
1623 /**
1624 * Enables a [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API)
1625 * for this navigation. To apply specific styles during the transition, see
1626 * {@link useViewTransitionState}.
1627 */
1628 viewTransition?: boolean;
1629}
1630/**
1631 * A progressively enhanced HTML [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form)
1632 * that submits data to actions via [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/fetch),
1633 * activating pending states in {@link useNavigation} which enables advanced
1634 * user interfaces beyond a basic HTML [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form).
1635 * After a form's `action` completes, all data on the page is automatically
1636 * revalidated to keep the UI in sync with the data.
1637 *
1638 * Because it uses the HTML form API, server rendered pages are interactive at a
1639 * basic level before JavaScript loads. Instead of React Router managing the
1640 * submission, the browser manages the submission as well as the pending states
1641 * (like the spinning favicon). After JavaScript loads, React Router takes over
1642 * enabling web application user experiences.
1643 *
1644 * `Form` is most useful for submissions that should also change the URL or
1645 * otherwise add an entry to the browser history stack. For forms that shouldn't
1646 * manipulate the browser [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
1647 * stack, use {@link FetcherWithComponents.Form | `<fetcher.Form>`}.
1648 *
1649 * @example
1650 * import { Form } from "react-router";
1651 *
1652 * function NewEvent() {
1653 * return (
1654 * <Form action="/events" method="post">
1655 * <input name="title" type="text" />
1656 * <input name="description" type="text" />
1657 * </Form>
1658 * );
1659 * }
1660 *
1661 * @public
1662 * @category Components
1663 * @mode framework
1664 * @mode data
1665 * @param {FormProps.action} action n/a
1666 * @param {FormProps.discover} discover n/a
1667 * @param {FormProps.encType} encType n/a
1668 * @param {FormProps.fetcherKey} fetcherKey n/a
1669 * @param {FormProps.method} method n/a
1670 * @param {FormProps.navigate} navigate n/a
1671 * @param {FormProps.onSubmit} onSubmit n/a
1672 * @param {FormProps.preventScrollReset} preventScrollReset n/a
1673 * @param {FormProps.relative} relative n/a
1674 * @param {FormProps.reloadDocument} reloadDocument n/a
1675 * @param {FormProps.replace} replace n/a
1676 * @param {FormProps.state} state n/a
1677 * @param {FormProps.viewTransition} viewTransition n/a
1678 * @param {FormProps.unstable_defaultShouldRevalidate} unstable_defaultShouldRevalidate n/a
1679 * @returns A progressively enhanced [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) component
1680 */
1681declare const Form: React.ForwardRefExoticComponent<FormProps & React.RefAttributes<HTMLFormElement>>;
1682type ScrollRestorationProps = ScriptsProps & {
1683 /**
1684 * A function that returns a key to use for scroll restoration. This is useful
1685 * for custom scroll restoration logic, such as using only the pathname so
1686 * that later navigations to prior paths will restore the scroll. Defaults to
1687 * `location.key`. See {@link GetScrollRestorationKeyFunction}.
1688 *
1689 * ```tsx
1690 * <ScrollRestoration
1691 * getKey={(location, matches) => {
1692 * // Restore based on a unique location key (default behavior)
1693 * return location.key
1694 *
1695 * // Restore based on pathname
1696 * return location.pathname
1697 * }}
1698 * />
1699 * ```
1700 */
1701 getKey?: GetScrollRestorationKeyFunction;
1702 /**
1703 * The key to use for storing scroll positions in [`sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage).
1704 * Defaults to `"react-router-scroll-positions"`.
1705 */
1706 storageKey?: string;
1707};
1708/**
1709 * Emulates the browser's scroll restoration on location changes. Apps should only render one of these, right before the {@link Scripts} component.
1710 *
1711 * ```tsx
1712 * import { ScrollRestoration } from "react-router";
1713 *
1714 * export default function Root() {
1715 * return (
1716 * <html>
1717 * <body>
1718 * <ScrollRestoration />
1719 * <Scripts />
1720 * </body>
1721 * </html>
1722 * );
1723 * }
1724 * ```
1725 *
1726 * This component renders an inline `<script>` to prevent scroll flashing. The `nonce` prop will be passed down to the script tag to allow CSP nonce usage.
1727 *
1728 * ```tsx
1729 * <ScrollRestoration nonce={cspNonce} />
1730 * ```
1731 *
1732 * @public
1733 * @category Components
1734 * @mode framework
1735 * @mode data
1736 * @param props Props
1737 * @param {ScrollRestorationProps.getKey} props.getKey n/a
1738 * @param {ScriptsProps.nonce} props.nonce n/a
1739 * @param {ScrollRestorationProps.storageKey} props.storageKey n/a
1740 * @returns A [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)
1741 * tag that restores scroll positions on navigation.
1742 */
1743declare function ScrollRestoration({ getKey, storageKey, ...props }: ScrollRestorationProps): React.JSX.Element | null;
1744declare namespace ScrollRestoration {
1745 var displayName: string;
1746}
1747/**
1748 * Handles the click behavior for router {@link Link | `<Link>`} components.This
1749 * is useful if you need to create custom {@link Link | `<Link>`} components with
1750 * the same click behavior we use in our exported {@link Link | `<Link>`}.
1751 *
1752 * @public
1753 * @category Hooks
1754 * @param to The URL to navigate to, can be a string or a partial {@link Path}.
1755 * @param options Options
1756 * @param options.preventScrollReset Whether to prevent the scroll position from
1757 * being reset to the top of the viewport on completion of the navigation when
1758 * using the {@link ScrollRestoration} component. Defaults to `false`.
1759 * @param options.relative The {@link RelativeRoutingType | relative routing type}
1760 * to use for the link. Defaults to `"route"`.
1761 * @param options.replace Whether to replace the current [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
1762 * entry instead of pushing a new one. Defaults to `false`.
1763 * @param options.state The state to add to the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
1764 * entry for this navigation. Defaults to `undefined`.
1765 * @param options.target The target attribute for the link. Defaults to `undefined`.
1766 * @param options.viewTransition Enables a [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API)
1767 * for this navigation. To apply specific styles during the transition, see
1768 * {@link useViewTransitionState}. Defaults to `false`.
1769 * @param options.unstable_defaultShouldRevalidate Specify the default revalidation
1770 * behavior for the navigation. Defaults to `true`.
1771 * @param options.unstable_useTransitions Wraps the navigation in
1772 * [`React.startTransition`](https://react.dev/reference/react/startTransition)
1773 * for concurrent rendering. Defaults to `false`.
1774 * @returns A click handler function that can be used in a custom {@link Link} component.
1775 */
1776declare function useLinkClickHandler<E extends Element = HTMLAnchorElement>(to: To, { target, replace: replaceProp, state, preventScrollReset, relative, viewTransition, unstable_defaultShouldRevalidate, unstable_useTransitions, }?: {
1777 target?: React.HTMLAttributeAnchorTarget;
1778 replace?: boolean;
1779 state?: any;
1780 preventScrollReset?: boolean;
1781 relative?: RelativeRoutingType;
1782 viewTransition?: boolean;
1783 unstable_defaultShouldRevalidate?: boolean;
1784 unstable_useTransitions?: boolean;
1785}): (event: React.MouseEvent<E, MouseEvent>) => void;
1786/**
1787 * Returns a tuple of the current URL's [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
1788 * and a function to update them. Setting the search params causes a navigation.
1789 *
1790 * ```tsx
1791 * import { useSearchParams } from "react-router";
1792 *
1793 * export function SomeComponent() {
1794 * const [searchParams, setSearchParams] = useSearchParams();
1795 * // ...
1796 * }
1797 * ```
1798 *
1799 * ### `setSearchParams` function
1800 *
1801 * The second element of the tuple is a function that can be used to update the
1802 * search params. It accepts the same types as `defaultInit` and will cause a
1803 * navigation to the new URL.
1804 *
1805 * ```tsx
1806 * let [searchParams, setSearchParams] = useSearchParams();
1807 *
1808 * // a search param string
1809 * setSearchParams("?tab=1");
1810 *
1811 * // a shorthand object
1812 * setSearchParams({ tab: "1" });
1813 *
1814 * // object keys can be arrays for multiple values on the key
1815 * setSearchParams({ brand: ["nike", "reebok"] });
1816 *
1817 * // an array of tuples
1818 * setSearchParams([["tab", "1"]]);
1819 *
1820 * // a `URLSearchParams` object
1821 * setSearchParams(new URLSearchParams("?tab=1"));
1822 * ```
1823 *
1824 * It also supports a function callback like React's
1825 * [`setState`](https://react.dev/reference/react/useState#setstate):
1826 *
1827 * ```tsx
1828 * setSearchParams((searchParams) => {
1829 * searchParams.set("tab", "2");
1830 * return searchParams;
1831 * });
1832 * ```
1833 *
1834 * <docs-warning>The function callback version of `setSearchParams` does not support
1835 * the [queueing](https://react.dev/reference/react/useState#setstate-parameters)
1836 * logic that React's `setState` implements. Multiple calls to `setSearchParams`
1837 * in the same tick will not build on the prior value. If you need this behavior,
1838 * you can use `setState` manually.</docs-warning>
1839 *
1840 * ### Notes
1841 *
1842 * Note that `searchParams` is a stable reference, so you can reliably use it
1843 * as a dependency in React's [`useEffect`](https://react.dev/reference/react/useEffect)
1844 * hooks.
1845 *
1846 * ```tsx
1847 * useEffect(() => {
1848 * console.log(searchParams.get("tab"));
1849 * }, [searchParams]);
1850 * ```
1851 *
1852 * However, this also means it's mutable. If you change the object without
1853 * calling `setSearchParams`, its values will change between renders if some
1854 * other state causes the component to re-render and URL will not reflect the
1855 * values.
1856 *
1857 * @public
1858 * @category Hooks
1859 * @param defaultInit
1860 * You can initialize the search params with a default value, though it **will
1861 * not** change the URL on the first render.
1862 *
1863 * ```tsx
1864 * // a search param string
1865 * useSearchParams("?tab=1");
1866 *
1867 * // a shorthand object
1868 * useSearchParams({ tab: "1" });
1869 *
1870 * // object keys can be arrays for multiple values on the key
1871 * useSearchParams({ brand: ["nike", "reebok"] });
1872 *
1873 * // an array of tuples
1874 * useSearchParams([["tab", "1"]]);
1875 *
1876 * // a `URLSearchParams` object
1877 * useSearchParams(new URLSearchParams("?tab=1"));
1878 * ```
1879 * @returns A tuple of the current [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
1880 * and a function to update them.
1881 */
1882declare function useSearchParams(defaultInit?: URLSearchParamsInit): [URLSearchParams, SetURLSearchParams];
1883/**
1884 * Sets new search params and causes a navigation when called.
1885 *
1886 * ```tsx
1887 * <button
1888 * onClick={() => {
1889 * const params = new URLSearchParams();
1890 * params.set("someKey", "someValue");
1891 * setSearchParams(params, {
1892 * preventScrollReset: true,
1893 * });
1894 * }}
1895 * />
1896 * ```
1897 *
1898 * It also supports a function for setting new search params.
1899 *
1900 * ```tsx
1901 * <button
1902 * onClick={() => {
1903 * setSearchParams((prev) => {
1904 * prev.set("someKey", "someValue");
1905 * return prev;
1906 * });
1907 * }}
1908 * />
1909 * ```
1910 */
1911type SetURLSearchParams = (nextInit?: URLSearchParamsInit | ((prev: URLSearchParams) => URLSearchParamsInit), navigateOpts?: NavigateOptions) => void;
1912/**
1913 * Submits a HTML [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form)
1914 * to the server without reloading the page.
1915 */
1916interface SubmitFunction {
1917 (
1918 /**
1919 * Can be multiple types of elements and objects
1920 *
1921 * **[`HTMLFormElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement)**
1922 *
1923 * ```tsx
1924 * <Form
1925 * onSubmit={(event) => {
1926 * submit(event.currentTarget);
1927 * }}
1928 * />
1929 * ```
1930 *
1931 * **[`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)**
1932 *
1933 * ```tsx
1934 * const formData = new FormData();
1935 * formData.append("myKey", "myValue");
1936 * submit(formData, { method: "post" });
1937 * ```
1938 *
1939 * **Plain object that will be serialized as [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)**
1940 *
1941 * ```tsx
1942 * submit({ myKey: "myValue" }, { method: "post" });
1943 * ```
1944 *
1945 * **Plain object that will be serialized as JSON**
1946 *
1947 * ```tsx
1948 * submit(
1949 * { myKey: "myValue" },
1950 * { method: "post", encType: "application/json" }
1951 * );
1952 * ```
1953 */
1954 target: SubmitTarget,
1955 /**
1956 * Options that override the [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form)'s
1957 * own attributes. Required when submitting arbitrary data without a backing
1958 * [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form).
1959 */
1960 options?: SubmitOptions): Promise<void>;
1961}
1962/**
1963 * Submits a fetcher [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) to the server without reloading the page.
1964 */
1965interface FetcherSubmitFunction {
1966 (
1967 /**
1968 * Can be multiple types of elements and objects
1969 *
1970 * **[`HTMLFormElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement)**
1971 *
1972 * ```tsx
1973 * <fetcher.Form
1974 * onSubmit={(event) => {
1975 * fetcher.submit(event.currentTarget);
1976 * }}
1977 * />
1978 * ```
1979 *
1980 * **[`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)**
1981 *
1982 * ```tsx
1983 * const formData = new FormData();
1984 * formData.append("myKey", "myValue");
1985 * fetcher.submit(formData, { method: "post" });
1986 * ```
1987 *
1988 * **Plain object that will be serialized as [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)**
1989 *
1990 * ```tsx
1991 * fetcher.submit({ myKey: "myValue" }, { method: "post" });
1992 * ```
1993 *
1994 * **Plain object that will be serialized as JSON**
1995 *
1996 * ```tsx
1997 * fetcher.submit(
1998 * { myKey: "myValue" },
1999 * { method: "post", encType: "application/json" }
2000 * );
2001 * ```
2002 */
2003 target: SubmitTarget, options?: FetcherSubmitOptions): Promise<void>;
2004}
2005/**
2006 * The imperative version of {@link Form | `<Form>`} that lets you submit a form
2007 * from code instead of a user interaction.
2008 *
2009 * @example
2010 * import { useSubmit } from "react-router";
2011 *
2012 * function SomeComponent() {
2013 * const submit = useSubmit();
2014 * return (
2015 * <Form onChange={(event) => submit(event.currentTarget)} />
2016 * );
2017 * }
2018 *
2019 * @public
2020 * @category Hooks
2021 * @mode framework
2022 * @mode data
2023 * @returns A function that can be called to submit a {@link Form} imperatively.
2024 */
2025declare function useSubmit(): SubmitFunction;
2026/**
2027 * Resolves the URL to the closest route in the component hierarchy instead of
2028 * the current URL of the app.
2029 *
2030 * This is used internally by {@link Form} to resolve the `action` to the closest
2031 * route, but can be used generically as well.
2032 *
2033 * @example
2034 * import { useFormAction } from "react-router";
2035 *
2036 * function SomeComponent() {
2037 * // closest route URL
2038 * let action = useFormAction();
2039 *
2040 * // closest route URL + "destroy"
2041 * let destroyAction = useFormAction("destroy");
2042 * }
2043 *
2044 * @public
2045 * @category Hooks
2046 * @mode framework
2047 * @mode data
2048 * @param action The action to append to the closest route URL. Defaults to the
2049 * closest route URL.
2050 * @param options Options
2051 * @param options.relative The relative routing type to use when resolving the
2052 * action. Defaults to `"route"`.
2053 * @returns The resolved action URL.
2054 */
2055declare function useFormAction(action?: string, { relative }?: {
2056 relative?: RelativeRoutingType;
2057}): string;
2058/**
2059 * The return value {@link useFetcher} that keeps track of the state of a fetcher.
2060 *
2061 * ```tsx
2062 * let fetcher = useFetcher();
2063 * ```
2064 */
2065type FetcherWithComponents<TData> = Fetcher<TData> & {
2066 /**
2067 * Just like {@link Form} except it doesn't cause a navigation.
2068 *
2069 * ```tsx
2070 * function SomeComponent() {
2071 * const fetcher = useFetcher()
2072 * return (
2073 * <fetcher.Form method="post" action="/some/route">
2074 * <input type="text" />
2075 * </fetcher.Form>
2076 * )
2077 * }
2078 * ```
2079 */
2080 Form: React.ForwardRefExoticComponent<FetcherFormProps & React.RefAttributes<HTMLFormElement>>;
2081 /**
2082 * Loads data from a route. Useful for loading data imperatively inside user
2083 * events outside a normal button or form, like a combobox or search input.
2084 *
2085 * ```tsx
2086 * let fetcher = useFetcher()
2087 *
2088 * <input onChange={e => {
2089 * fetcher.load(`/search?q=${e.target.value}`)
2090 * }} />
2091 * ```
2092 */
2093 load: (href: string, opts?: {
2094 /**
2095 * Wraps the initial state update for this `fetcher.load` in a
2096 * [`ReactDOM.flushSync`](https://react.dev/reference/react-dom/flushSync)
2097 * call instead of the default [`React.startTransition`](https://react.dev/reference/react/startTransition).
2098 * This allows you to perform synchronous DOM actions immediately after the
2099 * update is flushed to the DOM.
2100 */
2101 flushSync?: boolean;
2102 }) => Promise<void>;
2103 /**
2104 * Reset a fetcher back to an empty/idle state.
2105 *
2106 * If the fetcher is currently in-flight, the
2107 * [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController)
2108 * will be aborted with the `reason`, if provided.
2109 *
2110 * @param reason Optional `reason` to provide to [`AbortController.abort()`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort)
2111 * @returns void
2112 */
2113 reset: (opts?: {
2114 reason?: unknown;
2115 }) => void;
2116 /**
2117 * Submits form data to a route. While multiple nested routes can match a URL, only the leaf route will be called.
2118 *
2119 * The `formData` can be multiple types:
2120 *
2121 * - [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
2122 * A `FormData` instance.
2123 * - [`HTMLFormElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement)
2124 * A [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) DOM element.
2125 * - `Object`
2126 * An object of key/value-pairs that will be converted to a [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
2127 * instance by default. You can pass a more complex object and serialize it
2128 * as JSON by specifying `encType: "application/json"`. See
2129 * {@link useSubmit} for more details.
2130 *
2131 * If the method is `GET`, then the route [`loader`](../../start/framework/route-module#loader)
2132 * is being called and with the `formData` serialized to the url as [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams).
2133 * If `DELETE`, `PATCH`, `POST`, or `PUT`, then the route [`action`](../../start/framework/route-module#action)
2134 * is being called with `formData` as the body.
2135 *
2136 * ```tsx
2137 * // Submit a FormData instance (GET request)
2138 * const formData = new FormData();
2139 * fetcher.submit(formData);
2140 *
2141 * // Submit the HTML form element
2142 * fetcher.submit(event.currentTarget.form, {
2143 * method: "POST",
2144 * });
2145 *
2146 * // Submit key/value JSON as a FormData instance
2147 * fetcher.submit(
2148 * { serialized: "values" },
2149 * { method: "POST" }
2150 * );
2151 *
2152 * // Submit raw JSON
2153 * fetcher.submit(
2154 * {
2155 * deeply: {
2156 * nested: {
2157 * json: "values",
2158 * },
2159 * },
2160 * },
2161 * {
2162 * method: "POST",
2163 * encType: "application/json",
2164 * }
2165 * );
2166 * ```
2167 */
2168 submit: FetcherSubmitFunction;
2169};
2170/**
2171 * Useful for creating complex, dynamic user interfaces that require multiple,
2172 * concurrent data interactions without causing a navigation.
2173 *
2174 * Fetchers track their own, independent state and can be used to load data, submit
2175 * forms, and generally interact with [`action`](../../start/framework/route-module#action)
2176 * and [`loader`](../../start/framework/route-module#loader) functions.
2177 *
2178 * @example
2179 * import { useFetcher } from "react-router"
2180 *
2181 * function SomeComponent() {
2182 * let fetcher = useFetcher()
2183 *
2184 * // states are available on the fetcher
2185 * fetcher.state // "idle" | "loading" | "submitting"
2186 * fetcher.data // the data returned from the action or loader
2187 *
2188 * // render a form
2189 * <fetcher.Form method="post" />
2190 *
2191 * // load data
2192 * fetcher.load("/some/route")
2193 *
2194 * // submit data
2195 * fetcher.submit(someFormRef, { method: "post" })
2196 * fetcher.submit(someData, {
2197 * method: "post",
2198 * encType: "application/json"
2199 * })
2200 *
2201 * // reset fetcher
2202 * fetcher.reset()
2203 * }
2204 *
2205 * @public
2206 * @category Hooks
2207 * @mode framework
2208 * @mode data
2209 * @param options Options
2210 * @param options.key A unique key to identify the fetcher.
2211 *
2212 *
2213 * By default, `useFetcher` generates a unique fetcher scoped to that component.
2214 * If you want to identify a fetcher with your own key such that you can access
2215 * it from elsewhere in your app, you can do that with the `key` option:
2216 *
2217 * ```tsx
2218 * function SomeComp() {
2219 * let fetcher = useFetcher({ key: "my-key" })
2220 * // ...
2221 * }
2222 *
2223 * // Somewhere else
2224 * function AnotherComp() {
2225 * // this will be the same fetcher, sharing the state across the app
2226 * let fetcher = useFetcher({ key: "my-key" });
2227 * // ...
2228 * }
2229 * ```
2230 * @returns A {@link FetcherWithComponents} object that contains the fetcher's state, data, and components for submitting forms and loading data.
2231 */
2232declare function useFetcher<T = any>({ key, }?: {
2233 key?: string;
2234}): FetcherWithComponents<SerializeFrom<T>>;
2235/**
2236 * Returns an array of all in-flight {@link Fetcher}s. This is useful for components
2237 * throughout the app that didn't create the fetchers but want to use their submissions
2238 * to participate in optimistic UI.
2239 *
2240 * @example
2241 * import { useFetchers } from "react-router";
2242 *
2243 * function SomeComponent() {
2244 * const fetchers = useFetchers();
2245 * fetchers[0].formData; // FormData
2246 * fetchers[0].state; // etc.
2247 * // ...
2248 * }
2249 *
2250 * @public
2251 * @category Hooks
2252 * @mode framework
2253 * @mode data
2254 * @returns An array of all in-flight {@link Fetcher}s, each with a unique `key`
2255 * property.
2256 */
2257declare function useFetchers(): (Fetcher & {
2258 key: string;
2259})[];
2260/**
2261 * When rendered inside a {@link RouterProvider}, will restore scroll positions
2262 * on navigations
2263 *
2264 * <!--
2265 * Not marked `@public` because we only export as UNSAFE_ and therefore we don't
2266 * maintain an .md file for this hook
2267 * -->
2268 *
2269 * @name UNSAFE_useScrollRestoration
2270 * @category Hooks
2271 * @mode framework
2272 * @mode data
2273 * @param options Options
2274 * @param options.getKey A function that returns a key to use for scroll restoration.
2275 * This is useful for custom scroll restoration logic, such as using only the pathname
2276 * so that subsequent navigations to prior paths will restore the scroll. Defaults
2277 * to `location.key`.
2278 * @param options.storageKey The key to use for storing scroll positions in
2279 * `sessionStorage`. Defaults to `"react-router-scroll-positions"`.
2280 * @returns {void}
2281 */
2282declare function useScrollRestoration({ getKey, storageKey, }?: {
2283 getKey?: GetScrollRestorationKeyFunction;
2284 storageKey?: string;
2285}): void;
2286/**
2287 * Set up a callback to be fired on [Window's `beforeunload` event](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event).
2288 *
2289 * @public
2290 * @category Hooks
2291 * @param callback The callback to be called when the [`beforeunload` event](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event)
2292 * is fired.
2293 * @param options Options
2294 * @param options.capture If `true`, the event will be captured during the capture
2295 * phase. Defaults to `false`.
2296 * @returns {void}
2297 */
2298declare function useBeforeUnload(callback: (event: BeforeUnloadEvent) => any, options?: {
2299 capture?: boolean;
2300}): void;
2301/**
2302 * Wrapper around {@link useBlocker} to show a [`window.confirm`](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm)
2303 * prompt to users instead of building a custom UI with {@link useBlocker}.
2304 *
2305 * The `unstable_` flag will not be removed because this technique has a lot of
2306 * rough edges and behaves very differently (and incorrectly sometimes) across
2307 * browsers if users click addition back/forward navigations while the
2308 * confirmation is open. Use at your own risk.
2309 *
2310 * @example
2311 * function ImportantForm() {
2312 * let [value, setValue] = React.useState("");
2313 *
2314 * // Block navigating elsewhere when data has been entered into the input
2315 * unstable_usePrompt({
2316 * message: "Are you sure?",
2317 * when: ({ currentLocation, nextLocation }) =>
2318 * value !== "" &&
2319 * currentLocation.pathname !== nextLocation.pathname,
2320 * });
2321 *
2322 * return (
2323 * <Form method="post">
2324 * <label>
2325 * Enter some important data:
2326 * <input
2327 * name="data"
2328 * value={value}
2329 * onChange={(e) => setValue(e.target.value)}
2330 * />
2331 * </label>
2332 * <button type="submit">Save</button>
2333 * </Form>
2334 * );
2335 * }
2336 *
2337 * @name unstable_usePrompt
2338 * @public
2339 * @category Hooks
2340 * @mode framework
2341 * @mode data
2342 * @param options Options
2343 * @param options.message The message to show in the confirmation dialog.
2344 * @param options.when A boolean or a function that returns a boolean indicating
2345 * whether to block the navigation. If a function is provided, it will receive an
2346 * object with `currentLocation` and `nextLocation` properties.
2347 * @returns {void}
2348 */
2349declare function usePrompt({ when, message, }: {
2350 when: boolean | BlockerFunction;
2351 message: string;
2352}): void;
2353/**
2354 * This hook returns `true` when there is an active [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API)
2355 * to the specified location. This can be used to apply finer-grained styles to
2356 * elements to further customize the view transition. This requires that view
2357 * transitions have been enabled for the given navigation via {@link LinkProps.viewTransition}
2358 * (or the `Form`, `submit`, or `navigate` call)
2359 *
2360 * @public
2361 * @category Hooks
2362 * @mode framework
2363 * @mode data
2364 * @param to The {@link To} location to check for an active [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API).
2365 * @param options Options
2366 * @param options.relative The relative routing type to use when resolving the
2367 * `to` location, defaults to `"route"`. See {@link RelativeRoutingType} for
2368 * more details.
2369 * @returns `true` if there is an active [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API)
2370 * to the specified {@link Location}, otherwise `false`.
2371 */
2372declare function useViewTransitionState(to: To, { relative }?: {
2373 relative?: RelativeRoutingType;
2374}): boolean;
2375
2376/**
2377 * @category Types
2378 */
2379interface StaticRouterProps {
2380 /**
2381 * The base URL for the static router (default: `/`)
2382 */
2383 basename?: string;
2384 /**
2385 * The child elements to render inside the static router
2386 */
2387 children?: React.ReactNode;
2388 /**
2389 * The {@link Location} to render the static router at (default: `/`)
2390 */
2391 location: Partial<Location> | string;
2392}
2393/**
2394 * A {@link Router | `<Router>`} that may not navigate to any other {@link Location}.
2395 * This is useful on the server where there is no stateful UI.
2396 *
2397 * @public
2398 * @category Declarative Routers
2399 * @mode declarative
2400 * @param props Props
2401 * @param {StaticRouterProps.basename} props.basename n/a
2402 * @param {StaticRouterProps.children} props.children n/a
2403 * @param {StaticRouterProps.location} props.location n/a
2404 * @returns A React element that renders the static {@link Router | `<Router>`}
2405 */
2406declare function StaticRouter({ basename, children, location: locationProp, }: StaticRouterProps): React.JSX.Element;
2407/**
2408 * @category Types
2409 */
2410interface StaticRouterProviderProps {
2411 /**
2412 * The {@link StaticHandlerContext} returned from {@link StaticHandler}'s
2413 * `query`
2414 */
2415 context: StaticHandlerContext;
2416 /**
2417 * The static {@link DataRouter} from {@link createStaticRouter}
2418 */
2419 router: Router;
2420 /**
2421 * Whether to hydrate the router on the client (default `true`)
2422 */
2423 hydrate?: boolean;
2424 /**
2425 * The [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
2426 * to use for the hydration [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)
2427 * tag
2428 */
2429 nonce?: string;
2430}
2431/**
2432 * A {@link DataRouter} that may not navigate to any other {@link Location}.
2433 * This is useful on the server where there is no stateful UI.
2434 *
2435 * @example
2436 * export async function handleRequest(request: Request) {
2437 * let { query, dataRoutes } = createStaticHandler(routes);
2438 * let context = await query(request));
2439 *
2440 * if (context instanceof Response) {
2441 * return context;
2442 * }
2443 *
2444 * let router = createStaticRouter(dataRoutes, context);
2445 * return new Response(
2446 * ReactDOMServer.renderToString(<StaticRouterProvider ... />),
2447 * { headers: { "Content-Type": "text/html" } }
2448 * );
2449 * }
2450 *
2451 * @public
2452 * @category Data Routers
2453 * @mode data
2454 * @param props Props
2455 * @param {StaticRouterProviderProps.context} props.context n/a
2456 * @param {StaticRouterProviderProps.hydrate} props.hydrate n/a
2457 * @param {StaticRouterProviderProps.nonce} props.nonce n/a
2458 * @param {StaticRouterProviderProps.router} props.router n/a
2459 * @returns A React element that renders the static router provider
2460 */
2461declare function StaticRouterProvider({ context, router, hydrate, nonce, }: StaticRouterProviderProps): React.JSX.Element;
2462type CreateStaticHandlerOptions = Omit<CreateStaticHandlerOptions$1, "mapRouteProperties">;
2463/**
2464 * Create a static handler to perform server-side data loading
2465 *
2466 * @example
2467 * export async function handleRequest(request: Request) {
2468 * let { query, dataRoutes } = createStaticHandler(routes);
2469 * let context = await query(request);
2470 *
2471 * if (context instanceof Response) {
2472 * return context;
2473 * }
2474 *
2475 * let router = createStaticRouter(dataRoutes, context);
2476 * return new Response(
2477 * ReactDOMServer.renderToString(<StaticRouterProvider ... />),
2478 * { headers: { "Content-Type": "text/html" } }
2479 * );
2480 * }
2481 *
2482 * @public
2483 * @category Data Routers
2484 * @mode data
2485 * @param routes The {@link RouteObject | route objects} to create a static
2486 * handler for
2487 * @param opts Options
2488 * @param opts.basename The base URL for the static handler (default: `/`)
2489 * @param opts.future Future flags for the static handler
2490 * @returns A static handler that can be used to query data for the provided
2491 * routes
2492 */
2493declare function createStaticHandler(routes: RouteObject[], opts?: CreateStaticHandlerOptions): StaticHandler;
2494/**
2495 * Create a static {@link DataRouter} for server-side rendering
2496 *
2497 * @example
2498 * export async function handleRequest(request: Request) {
2499 * let { query, dataRoutes } = createStaticHandler(routes);
2500 * let context = await query(request);
2501 *
2502 * if (context instanceof Response) {
2503 * return context;
2504 * }
2505 *
2506 * let router = createStaticRouter(dataRoutes, context);
2507 * return new Response(
2508 * ReactDOMServer.renderToString(<StaticRouterProvider ... />),
2509 * { headers: { "Content-Type": "text/html" } }
2510 * );
2511 * }
2512 *
2513 * @public
2514 * @category Data Routers
2515 * @mode data
2516 * @param routes The route objects to create a static {@link DataRouter} for
2517 * @param context The {@link StaticHandlerContext} returned from {@link StaticHandler}'s
2518 * `query`
2519 * @param opts Options
2520 * @param opts.future Future flags for the static {@link DataRouter}
2521 * @returns A static {@link DataRouter} that can be used to render the provided routes
2522 */
2523declare function createStaticRouter(routes: RouteObject[], context: StaticHandlerContext, opts?: {
2524 future?: Partial<FutureConfig$1>;
2525}): Router;
2526
2527export { type ScriptsProps as $, type AssetsManifest as A, type BrowserRouterProps as B, useViewTransitionState as C, type DOMRouterOpts as D, type EntryContext as E, type FutureConfig as F, type FetcherSubmitOptions as G, type HashRouterProps as H, type SubmitOptions as I, type SubmitTarget as J, createSearchParams as K, type LinkProps as L, type StaticRouterProps as M, type NavLinkProps as N, type StaticRouterProviderProps as O, type ParamKeyValuePair as P, createStaticHandler as Q, createStaticRouter as R, type ServerBuild as S, StaticRouter as T, type URLSearchParamsInit as U, StaticRouterProvider as V, Meta as W, Links as X, Scripts as Y, PrefetchPageLinks as Z, type LinksProps as _, type HistoryRouterProps as a, type PrefetchBehavior as a0, type DiscoverBehavior as a1, type HandleDataRequestFunction as a2, type HandleDocumentRequestFunction as a3, type HandleErrorFunction as a4, type ServerEntryModule as a5, FrameworkContext as a6, createClientRoutes as a7, createClientRoutesWithHMRRevalidationOptOut as a8, shouldHydrateRouteLoader as a9, useScrollRestoration as aa, type NavLinkRenderProps as b, type FetcherFormProps as c, type FormProps as d, type ScrollRestorationProps as e, type SetURLSearchParams as f, type SubmitFunction as g, type FetcherSubmitFunction as h, type FetcherWithComponents as i, createBrowserRouter as j, createHashRouter as k, BrowserRouter as l, HashRouter as m, Link as n, HistoryRouter as o, NavLink as p, Form as q, ScrollRestoration as r, useSearchParams as s, useSubmit as t, useLinkClickHandler as u, useFormAction as v, useFetcher as w, useFetchers as x, useBeforeUnload as y, usePrompt as z };
2528
\No newline at end of file