UNPKG

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