UNPKG

115 kBTypeScriptView Raw
1import { I as InitialEntry, T as To, i as RelativeRoutingType, w as NonIndexRouteObject, ag as LazyRouteFunction, q as IndexRouteObject, a as Location, A as Action, aD as Navigator, d as Router$1, V as RouterInit, aZ as FutureConfig$1, H as HydrationState, D as DataStrategyFunction, X as PatchRoutesOnNavigationFunction, p as RouteObject, aF as RouteMatch, o as Params, U as UIMatch, af as HTMLFormMethod, ad as FormEncType, a_ as RouteManifest, a$ as ServerRouteModule, z as MiddlewareEnabled, y as unstable_RouterContextProvider, x as AppLoadContext, ah as LoaderFunctionArgs, a7 as ActionFunctionArgs, e as RouteModules, Y as DataRouteObject, K as ClientLoaderFunction, a0 as StaticHandlerContext, aK as PageLinkDescriptor, b0 as History, $ as GetScrollRestorationKeyFunction, f as NavigateOptions, a1 as Fetcher, h as SerializeFrom, B as BlockerFunction, b1 as CreateStaticHandlerOptions$1, Z as StaticHandler } from './routeModules-BR2FO0ix.js';
2import * as React from 'react';
3
4declare function mapRouteProperties(route: RouteObject): Partial<RouteObject> & {
5 hasErrorBoundary: boolean;
6};
7declare const hydrationRouteProperties: (keyof RouteObject)[];
8/**
9 * @category Data Routers
10 */
11interface MemoryRouterOpts {
12 /**
13 * Basename path for the application.
14 */
15 basename?: string;
16 /**
17 * Function to provide the initial context values for all client side
18 * navigations/fetches
19 */
20 unstable_getContext?: RouterInit["unstable_getContext"];
21 /**
22 * Future flags to enable for the router.
23 */
24 future?: Partial<FutureConfig$1>;
25 /**
26 * Hydration data to initialize the router with if you have already performed
27 * data loading on the server.
28 */
29 hydrationData?: HydrationState;
30 /**
31 * Initial entries in the in-memory history stack
32 */
33 initialEntries?: InitialEntry[];
34 /**
35 * Index of {@link initialEntries} the application should initialize to
36 */
37 initialIndex?: number;
38 /**
39 * Override the default data strategy of loading in parallel.
40 * Only intended for advanced usage.
41 */
42 dataStrategy?: DataStrategyFunction;
43 /**
44 * Lazily define portions of the route tree on navigations.
45 */
46 patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;
47}
48/**
49 * Create a new {@link DataRouter} that manages the application path using an
50 * in-memory [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
51 * stack. Useful for non-browser environments without a DOM API.
52 *
53 * @public
54 * @category Data Routers
55 * @mode data
56 * @param routes Application routes
57 * @param opts Options
58 * @param {MemoryRouterOpts.basename} opts.basename n/a
59 * @param {MemoryRouterOpts.dataStrategy} opts.dataStrategy n/a
60 * @param {MemoryRouterOpts.future} opts.future n/a
61 * @param {MemoryRouterOpts.unstable_getContext} opts.unstable_getContext n/a
62 * @param {MemoryRouterOpts.hydrationData} opts.hydrationData n/a
63 * @param {MemoryRouterOpts.initialEntries} opts.initialEntries n/a
64 * @param {MemoryRouterOpts.initialIndex} opts.initialIndex n/a
65 * @param {MemoryRouterOpts.patchRoutesOnNavigation} opts.patchRoutesOnNavigation n/a
66 * @returns An initialized {@link DataRouter} to pass to {@link RouterProvider | `<RouterProvider>`}
67 */
68declare function createMemoryRouter(routes: RouteObject[], opts?: MemoryRouterOpts): Router$1;
69/**
70 * @category Types
71 */
72interface RouterProviderProps {
73 /**
74 * The {@link DataRouter} instance to use for navigation and data fetching.
75 */
76 router: Router$1;
77 /**
78 * The [`ReactDOM.flushSync`](https://react.dev/reference/react-dom/flushSync)
79 * implementation to use for flushing updates.
80 *
81 * You usually don't have to worry about this:
82 * - The `RouterProvider` exported from `react-router/dom` handles this internally for you
83 * - If you are rendering in a non-DOM environment, you can import
84 * `RouterProvider` from `react-router` and ignore this prop
85 */
86 flushSync?: (fn: () => unknown) => undefined;
87}
88/**
89 * Render the UI for the given {@link DataRouter}. This component should
90 * typically be at the top of an app's element tree.
91 *
92 * @example
93 * import { createBrowserRouter } from "react-router";
94 * import { RouterProvider } from "react-router/dom";
95 * import { createRoot } from "react-dom/client";
96 *
97 * const router = createBrowserRouter(routes);
98 * createRoot(document.getElementById("root")).render(
99 * <RouterProvider router={router} />
100 * );
101 *
102 * @public
103 * @category Data Routers
104 * @mode data
105 * @param props Props
106 * @param {RouterProviderProps.flushSync} props.flushSync n/a
107 * @param {RouterProviderProps.router} props.router n/a
108 * @returns React element for the rendered router
109 */
110declare function RouterProvider({ router, flushSync: reactDomFlushSyncImpl, }: RouterProviderProps): React.ReactElement;
111/**
112 * @category Types
113 */
114interface MemoryRouterProps {
115 /**
116 * Application basename
117 */
118 basename?: string;
119 /**
120 * Nested {@link Route} elements describing the route tree
121 */
122 children?: React.ReactNode;
123 /**
124 * Initial entries in the in-memory history stack
125 */
126 initialEntries?: InitialEntry[];
127 /**
128 * Index of {@link initialEntries} the application should initialize to
129 */
130 initialIndex?: number;
131}
132/**
133 * A declarative {@link Router | `<Router>`} that stores all entries in memory.
134 *
135 * @public
136 * @category Declarative Routers
137 * @mode declarative
138 * @param props Props
139 * @param {MemoryRouterProps.basename} props.basename n/a
140 * @param {MemoryRouterProps.children} props.children n/a
141 * @param {MemoryRouterProps.initialEntries} props.initialEntries n/a
142 * @param {MemoryRouterProps.initialIndex} props.initialIndex n/a
143 * @returns A declarative in memory router for client side routing.
144 */
145declare function MemoryRouter({ basename, children, initialEntries, initialIndex, }: MemoryRouterProps): React.ReactElement;
146/**
147 * @category Types
148 */
149interface NavigateProps {
150 /**
151 * The path to navigate to. This can be a string or a {@link Path} object
152 */
153 to: To;
154 /**
155 * Whether to replace the current entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
156 * stack
157 */
158 replace?: boolean;
159 /**
160 * State to pass to the new {@link Location} to store in [`history.state`](https://developer.mozilla.org/en-US/docs/Web/API/History/state).
161 */
162 state?: any;
163 /**
164 * How to interpret relative routing in the {@link to} prop.
165 * See {@link RelativeRoutingType}.
166 */
167 relative?: RelativeRoutingType;
168}
169/**
170 * A component-based version of {@link useNavigate} to use in a
171 * [`React.Component` class](https://react.dev/reference/react/Component) where
172 * hooks cannot be used.
173 *
174 * It's recommended to avoid using this component in favor of {@link useNavigate}.
175 *
176 * @example
177 * <Navigate to="/tasks" />
178 *
179 * @public
180 * @category Components
181 * @param props Props
182 * @param {NavigateProps.relative} props.relative n/a
183 * @param {NavigateProps.replace} props.replace n/a
184 * @param {NavigateProps.state} props.state n/a
185 * @param {NavigateProps.to} props.to n/a
186 * @returns {void}
187 *
188 */
189declare function Navigate({ to, replace, state, relative, }: NavigateProps): null;
190/**
191 * @category Types
192 */
193interface OutletProps {
194 /**
195 * Provides a context value to the element tree below the outlet. Use when
196 * the parent route needs to provide values to child routes.
197 *
198 * ```tsx
199 * <Outlet context={myContextValue} />
200 * ```
201 *
202 * Access the context with {@link useOutletContext}.
203 */
204 context?: unknown;
205}
206/**
207 * Renders the matching child route of a parent route or nothing if no child
208 * route matches.
209 *
210 * @example
211 * import { Outlet } from "react-router";
212 *
213 * export default function SomeParent() {
214 * return (
215 * <div>
216 * <h1>Parent Content</h1>
217 * <Outlet />
218 * </div>
219 * );
220 * }
221 *
222 * @public
223 * @category Components
224 * @param props Props
225 * @param {OutletProps.context} props.context n/a
226 * @returns React element for the rendered outlet or `null` if no child route matches.
227 */
228declare function Outlet(props: OutletProps): React.ReactElement | null;
229/**
230 * @category Types
231 */
232interface PathRouteProps {
233 /**
234 * Whether the path should be case-sensitive. Defaults to `false`.
235 */
236 caseSensitive?: NonIndexRouteObject["caseSensitive"];
237 /**
238 * The path pattern to match. If unspecified or empty, then this becomes a
239 * layout route.
240 */
241 path?: NonIndexRouteObject["path"];
242 /**
243 * The unique identifier for this route (for use with {@link DataRouter}s)
244 */
245 id?: NonIndexRouteObject["id"];
246 /**
247 * A function that returns a promise that resolves to the route object.
248 * Used for code-splitting routes.
249 * See [`lazy`](../../start/data/route-object#lazy).
250 */
251 lazy?: LazyRouteFunction<NonIndexRouteObject>;
252 /**
253 * The route loader.
254 * See [`loader`](../../start/data/route-object#loader).
255 */
256 loader?: NonIndexRouteObject["loader"];
257 /**
258 * The route action.
259 * See [`action`](../../start/data/route-object#action).
260 */
261 action?: NonIndexRouteObject["action"];
262 hasErrorBoundary?: NonIndexRouteObject["hasErrorBoundary"];
263 /**
264 * The route shouldRevalidate function.
265 * See [`shouldRevalidate`](../../start/data/route-object#shouldRevalidate).
266 */
267 shouldRevalidate?: NonIndexRouteObject["shouldRevalidate"];
268 /**
269 * The route handle.
270 */
271 handle?: NonIndexRouteObject["handle"];
272 /**
273 * Whether this is an index route.
274 */
275 index?: false;
276 /**
277 * Child Route components
278 */
279 children?: React.ReactNode;
280 /**
281 * The React element to render when this Route matches.
282 * Mutually exclusive with {@link Component}.
283 */
284 element?: React.ReactNode | null;
285 /**
286 * The React element to render while this router is loading data.
287 * Mutually exclusive with {@link HydrateFallback}.
288 */
289 hydrateFallbackElement?: React.ReactNode | null;
290 /**
291 * The React element to render at this route if an error occurs.
292 * Mutually exclusive with {@link ErrorBoundary}.
293 */
294 errorElement?: React.ReactNode | null;
295 /**
296 * The React Component to render when this route matches.
297 * Mutually exclusive with {@link element}.
298 */
299 Component?: React.ComponentType | null;
300 /**
301 * The React Component to render while this router is loading data.
302 * Mutually exclusive with {@link hydrateFallbackElement}.
303 */
304 HydrateFallback?: React.ComponentType | null;
305 /**
306 * The React Component to render at this route if an error occurs.
307 * Mutually exclusive with {@link errorElement}.
308 */
309 ErrorBoundary?: React.ComponentType | null;
310}
311/**
312 * @category Types
313 */
314interface LayoutRouteProps extends PathRouteProps {
315}
316/**
317 * @category Types
318 */
319interface IndexRouteProps {
320 /**
321 * Whether the path should be case-sensitive. Defaults to `false`.
322 */
323 caseSensitive?: IndexRouteObject["caseSensitive"];
324 /**
325 * The path pattern to match. If unspecified or empty, then this becomes a
326 * layout route.
327 */
328 path?: IndexRouteObject["path"];
329 /**
330 * The unique identifier for this route (for use with {@link DataRouter}s)
331 */
332 id?: IndexRouteObject["id"];
333 /**
334 * A function that returns a promise that resolves to the route object.
335 * Used for code-splitting routes.
336 * See [`lazy`](../../start/data/route-object#lazy).
337 */
338 lazy?: LazyRouteFunction<IndexRouteObject>;
339 /**
340 * The route loader.
341 * See [`loader`](../../start/data/route-object#loader).
342 */
343 loader?: IndexRouteObject["loader"];
344 /**
345 * The route action.
346 * See [`action`](../../start/data/route-object#action).
347 */
348 action?: IndexRouteObject["action"];
349 hasErrorBoundary?: IndexRouteObject["hasErrorBoundary"];
350 /**
351 * The route shouldRevalidate function.
352 * See [`shouldRevalidate`](../../start/data/route-object#shouldRevalidate).
353 */
354 shouldRevalidate?: IndexRouteObject["shouldRevalidate"];
355 /**
356 * The route handle.
357 */
358 handle?: IndexRouteObject["handle"];
359 /**
360 * Whether this is an index route.
361 */
362 index: true;
363 /**
364 * Child Route components
365 */
366 children?: undefined;
367 /**
368 * The React element to render when this Route matches.
369 * Mutually exclusive with {@link Component}.
370 */
371 element?: React.ReactNode | null;
372 /**
373 * The React element to render while this router is loading data.
374 * Mutually exclusive with {@link HydrateFallback}.
375 */
376 hydrateFallbackElement?: React.ReactNode | null;
377 /**
378 * The React element to render at this route if an error occurs.
379 * Mutually exclusive with {@link ErrorBoundary}.
380 */
381 errorElement?: React.ReactNode | null;
382 /**
383 * The React Component to render when this route matches.
384 * Mutually exclusive with {@link element}.
385 */
386 Component?: React.ComponentType | null;
387 /**
388 * The React Component to render while this router is loading data.
389 * Mutually exclusive with {@link hydrateFallbackElement}.
390 */
391 HydrateFallback?: React.ComponentType | null;
392 /**
393 * The React Component to render at this route if an error occurs.
394 * Mutually exclusive with {@link errorElement}.
395 */
396 ErrorBoundary?: React.ComponentType | null;
397}
398type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;
399/**
400 * Configures an element to render when a pattern matches the current location.
401 * It must be rendered within a {@link Routes} element. Note that these routes
402 * do not participate in data loading, actions, code splitting, or any other
403 * route module features.
404 *
405 * @example
406 * // Usually used in a declarative router
407 * function App() {
408 * return (
409 * <BrowserRouter>
410 * <Routes>
411 * <Route index element={<StepOne />} />
412 * <Route path="step-2" element={<StepTwo />} />
413 * <Route path="step-3" element={<StepThree />} />
414 * </Routes>
415 * </BrowserRouter>
416 * );
417 * }
418 *
419 * // But can be used with a data router as well if you prefer the JSX notation
420 * const routes = createRoutesFromElements(
421 * <>
422 * <Route index loader={step1Loader} Component={StepOne} />
423 * <Route path="step-2" loader={step2Loader} Component={StepTwo} />
424 * <Route path="step-3" loader={step3Loader} Component={StepThree} />
425 * </>
426 * );
427 *
428 * const router = createBrowserRouter(routes);
429 *
430 * function App() {
431 * return <RouterProvider router={router} />;
432 * }
433 *
434 * @public
435 * @category Components
436 * @param props Props
437 * @param {PathRouteProps.action} props.action n/a
438 * @param {PathRouteProps.caseSensitive} props.caseSensitive n/a
439 * @param {PathRouteProps.Component} props.Component n/a
440 * @param {PathRouteProps.children} props.children n/a
441 * @param {PathRouteProps.element} props.element n/a
442 * @param {PathRouteProps.ErrorBoundary} props.ErrorBoundary n/a
443 * @param {PathRouteProps.errorElement} props.errorElement n/a
444 * @param {PathRouteProps.handle} props.handle n/a
445 * @param {PathRouteProps.HydrateFallback} props.HydrateFallback n/a
446 * @param {PathRouteProps.hydrateFallbackElement} props.hydrateFallbackElement n/a
447 * @param {PathRouteProps.id} props.id n/a
448 * @param {PathRouteProps.index} props.index n/a
449 * @param {PathRouteProps.lazy} props.lazy n/a
450 * @param {PathRouteProps.loader} props.loader n/a
451 * @param {PathRouteProps.path} props.path n/a
452 * @param {PathRouteProps.shouldRevalidate} props.shouldRevalidate n/a
453 * @returns {void}
454 */
455declare function Route$1(props: RouteProps): React.ReactElement | null;
456/**
457 * @category Types
458 */
459interface RouterProps {
460 /**
461 * The base path for the application. This is prepended to all locations
462 */
463 basename?: string;
464 /**
465 * Nested {@link Route} elements describing the route tree
466 */
467 children?: React.ReactNode;
468 /**
469 * The location to match against. Defaults to the current location.
470 * This can be a string or a {@link Location} object.
471 */
472 location: Partial<Location> | string;
473 /**
474 * The type of navigation that triggered this location change.
475 * Defaults to {@link NavigationType.Pop}.
476 */
477 navigationType?: Action;
478 /**
479 * The navigator to use for navigation. This is usually a history object
480 * or a custom navigator that implements the {@link Navigator} interface.
481 */
482 navigator: Navigator;
483 /**
484 * Whether this router is static or not (used for SSR). If `true`, the router
485 * will not be reactive to location changes.
486 */
487 static?: boolean;
488}
489/**
490 * Provides location context for the rest of the app.
491 *
492 * Note: You usually won't render a `<Router>` directly. Instead, you'll render a
493 * router that is more specific to your environment such as a {@link BrowserRouter}
494 * in web browsers or a {@link ServerRouter} for server rendering.
495 *
496 * @public
497 * @category Declarative Routers
498 * @mode declarative
499 * @param props Props
500 * @param {RouterProps.basename} props.basename n/a
501 * @param {RouterProps.children} props.children n/a
502 * @param {RouterProps.location} props.location n/a
503 * @param {RouterProps.navigationType} props.navigationType n/a
504 * @param {RouterProps.navigator} props.navigator n/a
505 * @param {RouterProps.static} props.static n/a
506 * @returns React element for the rendered router or `null` if the location does
507 * not match the {@link props.basename}
508 */
509declare function Router({ basename: basenameProp, children, location: locationProp, navigationType, navigator, static: staticProp, }: RouterProps): React.ReactElement | null;
510/**
511 * @category Types
512 */
513interface RoutesProps {
514 /**
515 * Nested {@link Route} elements
516 */
517 children?: React.ReactNode;
518 /**
519 * The {@link Location} to match against. Defaults to the current location.
520 */
521 location?: Partial<Location> | string;
522}
523/**
524 * Renders a branch of {@link Route | `<Route>`s} that best matches the current
525 * location. Note that these routes do not participate in [data loading](../../start/framework/route-module#loader),
526 * [`action`](../../start/framework/route-module#action), code splitting, or
527 * any other [route module](../../start/framework/route-module) features.
528 *
529 * @example
530 * import { Route, Routes } from "react-router";
531 *
532 * <Routes>
533 * <Route index element={<StepOne />} />
534 * <Route path="step-2" element={<StepTwo />} />
535 * <Route path="step-3" element={<StepThree />}>
536 * </Routes>
537 *
538 * @public
539 * @category Components
540 * @param props Props
541 * @param {RoutesProps.children} props.children n/a
542 * @param {RoutesProps.location} props.location n/a
543 * @returns React element for the rendered routes or `null` if no route matches
544 */
545declare function Routes({ children, location, }: RoutesProps): React.ReactElement | null;
546interface AwaitResolveRenderFunction<Resolve = any> {
547 (data: Awaited<Resolve>): React.ReactNode;
548}
549/**
550 * @category Types
551 */
552interface AwaitProps<Resolve> {
553 /**
554 * When using a function, the resolved value is provided as the parameter.
555 *
556 * ```tsx [2]
557 * <Await resolve={reviewsPromise}>
558 * {(resolvedReviews) => <Reviews items={resolvedReviews} />}
559 * </Await>
560 * ```
561 *
562 * When using React elements, {@link useAsyncValue} will provide the
563 * resolved value:
564 *
565 * ```tsx [2]
566 * <Await resolve={reviewsPromise}>
567 * <Reviews />
568 * </Await>
569 *
570 * function Reviews() {
571 * const resolvedReviews = useAsyncValue();
572 * return <div>...</div>;
573 * }
574 * ```
575 */
576 children: React.ReactNode | AwaitResolveRenderFunction<Resolve>;
577 /**
578 * The error element renders instead of the `children` when the [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
579 * rejects.
580 *
581 * ```tsx
582 * <Await
583 * errorElement={<div>Oops</div>}
584 * resolve={reviewsPromise}
585 * >
586 * <Reviews />
587 * </Await>
588 * ```
589 *
590 * To provide a more contextual error, you can use the {@link useAsyncError} in a
591 * child component
592 *
593 * ```tsx
594 * <Await
595 * errorElement={<ReviewsError />}
596 * resolve={reviewsPromise}
597 * >
598 * <Reviews />
599 * </Await>
600 *
601 * function ReviewsError() {
602 * const error = useAsyncError();
603 * return <div>Error loading reviews: {error.message}</div>;
604 * }
605 * ```
606 *
607 * If you do not provide an `errorElement`, the rejected value will bubble up
608 * to the nearest route-level [`ErrorBoundary`](../../start/framework/route-module#errorboundary)
609 * and be accessible via the {@link useRouteError} hook.
610 */
611 errorElement?: React.ReactNode;
612 /**
613 * Takes a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
614 * returned from a [`loader`](../../start/framework/route-module#loader) to be
615 * resolved and rendered.
616 *
617 * ```tsx
618 * import { Await, useLoaderData } from "react-router";
619 *
620 * export async function loader() {
621 * let reviews = getReviews(); // not awaited
622 * let book = await getBook();
623 * return {
624 * book,
625 * reviews, // this is a promise
626 * };
627 * }
628 *
629 * export default function Book() {
630 * const {
631 * book,
632 * reviews, // this is the same promise
633 * } = useLoaderData();
634 *
635 * return (
636 * <div>
637 * <h1>{book.title}</h1>
638 * <p>{book.description}</p>
639 * <React.Suspense fallback={<ReviewsSkeleton />}>
640 * <Await
641 * // and is the promise we pass to Await
642 * resolve={reviews}
643 * >
644 * <Reviews />
645 * </Await>
646 * </React.Suspense>
647 * </div>
648 * );
649 * }
650 * ```
651 */
652 resolve: Resolve;
653}
654/**
655 * Used to render promise values with automatic error handling.
656 *
657 * **Note:** `<Await>` expects to be rendered inside a [`<React.Suspense>`](https://react.dev/reference/react/Suspense)
658 *
659 * @example
660 * import { Await, useLoaderData } from "react-router";
661 *
662 * export async function loader() {
663 * // not awaited
664 * const reviews = getReviews();
665 * // awaited (blocks the transition)
666 * const book = await fetch("/api/book").then((res) => res.json());
667 * return { book, reviews };
668 * }
669 *
670 * function Book() {
671 * const { book, reviews } = useLoaderData();
672 * return (
673 * <div>
674 * <h1>{book.title}</h1>
675 * <p>{book.description}</p>
676 * <React.Suspense fallback={<ReviewsSkeleton />}>
677 * <Await
678 * resolve={reviews}
679 * errorElement={
680 * <div>Could not load reviews 😬</div>
681 * }
682 * children={(resolvedReviews) => (
683 * <Reviews items={resolvedReviews} />
684 * )}
685 * />
686 * </React.Suspense>
687 * </div>
688 * );
689 * }
690 *
691 * @public
692 * @category Components
693 * @mode framework
694 * @mode data
695 * @param props Props
696 * @param {AwaitProps.children} props.children n/a
697 * @param {AwaitProps.errorElement} props.errorElement n/a
698 * @param {AwaitProps.resolve} props.resolve n/a
699 * @returns React element for the rendered awaited value
700 */
701declare function Await<Resolve>({ children, errorElement, resolve, }: AwaitProps<Resolve>): React.JSX.Element;
702/**
703 * Creates a route config from a React "children" object, which is usually
704 * either a `<Route>` element or an array of them. Used internally by
705 * `<Routes>` to create a route config from its children.
706 *
707 * @category Utils
708 * @mode data
709 * @param children The React children to convert into a route config
710 * @param parentPath The path of the parent route, used to generate unique IDs.
711 * @returns An array of {@link RouteObject}s that can be used with a {@link DataRouter}
712 */
713declare function createRoutesFromChildren(children: React.ReactNode, parentPath?: number[]): RouteObject[];
714/**
715 * Create route objects from JSX elements instead of arrays of objects.
716 *
717 * @example
718 * const routes = createRoutesFromElements(
719 * <>
720 * <Route index loader={step1Loader} Component={StepOne} />
721 * <Route path="step-2" loader={step2Loader} Component={StepTwo} />
722 * <Route path="step-3" loader={step3Loader} Component={StepThree} />
723 * </>
724 * );
725 *
726 * const router = createBrowserRouter(routes);
727 *
728 * function App() {
729 * return <RouterProvider router={router} />;
730 * }
731 *
732 * @name createRoutesFromElements
733 * @public
734 * @category Utils
735 * @mode data
736 * @param children The React children to convert into a route config
737 * @param parentPath The path of the parent route, used to generate unique IDs.
738 * This is used for internal recursion and is not intended to be used by the
739 * application developer.
740 * @returns An array of {@link RouteObject}s that can be used with a {@link DataRouter}
741 */
742declare const createRoutesFromElements: typeof createRoutesFromChildren;
743/**
744 * Renders the result of {@link matchRoutes} into a React element.
745 *
746 * @public
747 * @category Utils
748 * @param matches The array of {@link RouteMatch | route matches} to render
749 * @returns A React element that renders the matched routes or `null` if no matches
750 */
751declare function renderMatches(matches: RouteMatch[] | null): React.ReactElement | null;
752declare function useRouteComponentProps(): {
753 params: Readonly<Params<string>>;
754 loaderData: any;
755 actionData: any;
756 matches: UIMatch<unknown, unknown>[];
757};
758type RouteComponentProps = ReturnType<typeof useRouteComponentProps>;
759type RouteComponentType = React.ComponentType<RouteComponentProps>;
760declare function WithComponentProps({ children, }: {
761 children: React.ReactElement;
762}): React.ReactElement<any, string | React.JSXElementConstructor<any>>;
763declare function withComponentProps(Component: RouteComponentType): () => React.ReactElement<{
764 params: Readonly<Params<string>>;
765 loaderData: any;
766 actionData: any;
767 matches: UIMatch<unknown, unknown>[];
768}, string | React.JSXElementConstructor<any>>;
769declare function useHydrateFallbackProps(): {
770 params: Readonly<Params<string>>;
771 loaderData: any;
772 actionData: any;
773};
774type HydrateFallbackProps = ReturnType<typeof useHydrateFallbackProps>;
775type HydrateFallbackType = React.ComponentType<HydrateFallbackProps>;
776declare function WithHydrateFallbackProps({ children, }: {
777 children: React.ReactElement;
778}): React.ReactElement<any, string | React.JSXElementConstructor<any>>;
779declare function withHydrateFallbackProps(HydrateFallback: HydrateFallbackType): () => React.ReactElement<{
780 params: Readonly<Params<string>>;
781 loaderData: any;
782 actionData: any;
783}, string | React.JSXElementConstructor<any>>;
784declare function useErrorBoundaryProps(): {
785 params: Readonly<Params<string>>;
786 loaderData: any;
787 actionData: any;
788 error: unknown;
789};
790type ErrorBoundaryProps = ReturnType<typeof useErrorBoundaryProps>;
791type ErrorBoundaryType = React.ComponentType<ErrorBoundaryProps>;
792declare function WithErrorBoundaryProps({ children, }: {
793 children: React.ReactElement;
794}): React.ReactElement<any, string | React.JSXElementConstructor<any>>;
795declare function withErrorBoundaryProps(ErrorBoundary: ErrorBoundaryType): () => React.ReactElement<{
796 params: Readonly<Params<string>>;
797 loaderData: any;
798 actionData: any;
799 error: unknown;
800}, string | React.JSXElementConstructor<any>>;
801
802type ParamKeyValuePair = [string, string];
803type URLSearchParamsInit = string | ParamKeyValuePair[] | Record<string, string | string[]> | URLSearchParams;
804/**
805 Creates a URLSearchParams object using the given initializer.
806
807 This is identical to `new URLSearchParams(init)` except it also
808 supports arrays as values in the object form of the initializer
809 instead of just strings. This is convenient when you need multiple
810 values for a given key, but don't want to use an array initializer.
811
812 For example, instead of:
813
814 ```tsx
815 let searchParams = new URLSearchParams([
816 ['sort', 'name'],
817 ['sort', 'price']
818 ]);
819 ```
820 you can do:
821
822 ```
823 let searchParams = createSearchParams({
824 sort: ['name', 'price']
825 });
826 ```
827
828 @category Utils
829 */
830declare function createSearchParams(init?: URLSearchParamsInit): URLSearchParams;
831type JsonObject = {
832 [Key in string]: JsonValue;
833} & {
834 [Key in string]?: JsonValue | undefined;
835};
836type JsonArray = JsonValue[] | readonly JsonValue[];
837type JsonPrimitive = string | number | boolean | null;
838type JsonValue = JsonPrimitive | JsonObject | JsonArray;
839type SubmitTarget = HTMLFormElement | HTMLButtonElement | HTMLInputElement | FormData | URLSearchParams | JsonValue | null;
840/**
841 * Submit options shared by both navigations and fetchers
842 */
843interface SharedSubmitOptions {
844 /**
845 * The HTTP method used to submit the form. Overrides `<form method>`.
846 * Defaults to "GET".
847 */
848 method?: HTMLFormMethod;
849 /**
850 * The action URL path used to submit the form. Overrides `<form action>`.
851 * Defaults to the path of the current route.
852 */
853 action?: string;
854 /**
855 * The encoding used to submit the form. Overrides `<form encType>`.
856 * Defaults to "application/x-www-form-urlencoded".
857 */
858 encType?: FormEncType;
859 /**
860 * Determines whether the form action is relative to the route hierarchy or
861 * the pathname. Use this if you want to opt out of navigating the route
862 * hierarchy and want to instead route based on /-delimited URL segments
863 */
864 relative?: RelativeRoutingType;
865 /**
866 * In browser-based environments, prevent resetting scroll after this
867 * navigation when using the <ScrollRestoration> component
868 */
869 preventScrollReset?: boolean;
870 /**
871 * Enable flushSync for this submission's state updates
872 */
873 flushSync?: boolean;
874}
875/**
876 * Submit options available to fetchers
877 */
878interface FetcherSubmitOptions extends SharedSubmitOptions {
879}
880/**
881 * Submit options available to navigations
882 */
883interface SubmitOptions extends FetcherSubmitOptions {
884 /**
885 * Set `true` to replace the current entry in the browser's history stack
886 * instead of creating a new one (i.e. stay on "the same page"). Defaults
887 * to `false`.
888 */
889 replace?: boolean;
890 /**
891 * State object to add to the history stack entry for this navigation
892 */
893 state?: any;
894 /**
895 * Indicate a specific fetcherKey to use when using navigate=false
896 */
897 fetcherKey?: string;
898 /**
899 * navigate=false will use a fetcher instead of a navigation
900 */
901 navigate?: boolean;
902 /**
903 * Enable view transitions on this submission navigation
904 */
905 viewTransition?: boolean;
906}
907
908type ServerRouteManifest = RouteManifest<Omit<ServerRoute, "children">>;
909interface ServerRoute extends Route {
910 children: ServerRoute[];
911 module: ServerRouteModule;
912}
913
914type OptionalCriticalCss = CriticalCss | undefined;
915/**
916 * The output of the compiler for the server build.
917 */
918interface ServerBuild {
919 entry: {
920 module: ServerEntryModule;
921 };
922 routes: ServerRouteManifest;
923 assets: AssetsManifest;
924 basename?: string;
925 publicPath: string;
926 assetsBuildDirectory: string;
927 future: FutureConfig;
928 ssr: boolean;
929 unstable_getCriticalCss?: (args: {
930 pathname: string;
931 }) => OptionalCriticalCss | Promise<OptionalCriticalCss>;
932 /**
933 * @deprecated This is now done via a custom header during prerendering
934 */
935 isSpaMode: boolean;
936 prerender: string[];
937 routeDiscovery: {
938 mode: "lazy" | "initial";
939 manifestPath: string;
940 };
941}
942interface HandleDocumentRequestFunction {
943 (request: Request, responseStatusCode: number, responseHeaders: Headers, context: EntryContext, loadContext: MiddlewareEnabled extends true ? unstable_RouterContextProvider : AppLoadContext): Promise<Response> | Response;
944}
945interface HandleDataRequestFunction {
946 (response: Response, args: LoaderFunctionArgs | ActionFunctionArgs): Promise<Response> | Response;
947}
948interface HandleErrorFunction {
949 (error: unknown, args: LoaderFunctionArgs | ActionFunctionArgs): void;
950}
951/**
952 * A module that serves as the entry point for a Remix app during server
953 * rendering.
954 */
955interface ServerEntryModule {
956 default: HandleDocumentRequestFunction;
957 handleDataRequest?: HandleDataRequestFunction;
958 handleError?: HandleErrorFunction;
959 streamTimeout?: number;
960}
961
962interface Route {
963 index?: boolean;
964 caseSensitive?: boolean;
965 id: string;
966 parentId?: string;
967 path?: string;
968}
969interface EntryRoute extends Route {
970 hasAction: boolean;
971 hasLoader: boolean;
972 hasClientAction: boolean;
973 hasClientLoader: boolean;
974 hasClientMiddleware: boolean;
975 hasErrorBoundary: boolean;
976 imports?: string[];
977 css?: string[];
978 module: string;
979 clientActionModule: string | undefined;
980 clientLoaderModule: string | undefined;
981 clientMiddlewareModule: string | undefined;
982 hydrateFallbackModule: string | undefined;
983 parentId?: string;
984}
985declare function createClientRoutesWithHMRRevalidationOptOut(needsRevalidation: Set<string>, manifest: RouteManifest<EntryRoute>, routeModulesCache: RouteModules, initialState: HydrationState, ssr: boolean, isSpaMode: boolean): DataRouteObject[];
986declare 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[];
987declare function shouldHydrateRouteLoader(routeId: string, clientLoader: ClientLoaderFunction | undefined, hasLoader: boolean, isSpaMode: boolean): boolean;
988
989type SerializedError = {
990 message: string;
991 stack?: string;
992};
993interface FrameworkContextObject {
994 manifest: AssetsManifest;
995 routeModules: RouteModules;
996 criticalCss?: CriticalCss;
997 serverHandoffString?: string;
998 future: FutureConfig;
999 ssr: boolean;
1000 isSpaMode: boolean;
1001 routeDiscovery: ServerBuild["routeDiscovery"];
1002 serializeError?(error: Error): SerializedError;
1003 renderMeta?: {
1004 didRenderScripts?: boolean;
1005 streamCache?: Record<number, Promise<void> & {
1006 result?: {
1007 done: boolean;
1008 value: string;
1009 };
1010 error?: unknown;
1011 }>;
1012 };
1013}
1014interface EntryContext extends FrameworkContextObject {
1015 staticHandlerContext: StaticHandlerContext;
1016 serverHandoffStream?: ReadableStream<Uint8Array>;
1017}
1018interface FutureConfig {
1019 unstable_subResourceIntegrity: boolean;
1020 unstable_middleware: boolean;
1021}
1022type CriticalCss = string | {
1023 rel: "stylesheet";
1024 href: string;
1025};
1026interface AssetsManifest {
1027 entry: {
1028 imports: string[];
1029 module: string;
1030 };
1031 routes: RouteManifest<EntryRoute>;
1032 url: string;
1033 version: string;
1034 hmr?: {
1035 timestamp?: number;
1036 runtime: string;
1037 };
1038 sri?: Record<string, string> | true;
1039}
1040
1041declare const FrameworkContext: React.Context<FrameworkContextObject | undefined>;
1042/**
1043 * Defines the discovery behavior of the link:
1044 *
1045 * - "render" - default, discover the route when the link renders
1046 * - "none" - don't eagerly discover, only discover if the link is clicked
1047 */
1048type DiscoverBehavior = "render" | "none";
1049/**
1050 * Defines the prefetching behavior of the link:
1051 *
1052 * - "none": Never fetched
1053 * - "intent": Fetched when the user focuses or hovers the link
1054 * - "render": Fetched when the link is rendered
1055 * - "viewport": Fetched when the link is in the viewport
1056 */
1057type PrefetchBehavior = "intent" | "render" | "none" | "viewport";
1058/**
1059 * Renders all of the `<link>` tags created by the route module
1060 * [`links`](../../start/framework/route-module#links) export. You should render
1061 * it inside the `<head>` of your document.
1062 *
1063 * @example
1064 * import { Links } from "react-router";
1065 *
1066 * export default function Root() {
1067 * return (
1068 * <html>
1069 * <head>
1070 * <Links />
1071 * </head>
1072 * <body></body>
1073 * </html>
1074 * );
1075 * }
1076 *
1077 * @public
1078 * @category Components
1079 * @mode framework
1080 * @returns A collection of React elements for `<link>` tags
1081 */
1082declare function Links(): React.JSX.Element;
1083/**
1084 * Renders `<link rel=prefetch|modulepreload>` tags for modules and data of
1085 * another page to enable an instant navigation to that page.
1086 * [`<Link prefetch>`](../../components/Link#prefetch) uses this internally, but
1087 * you can render it to prefetch a page for any other reason.
1088 *
1089 * For example, you may render one of this as the user types into a search field
1090 * to prefetch search results before they click through to their selection.
1091 *
1092 * @example
1093 * import { PrefetchPageLinks } from "react-router";
1094 *
1095 * <PrefetchPageLinks page="/absolute/path" />
1096 *
1097 * @public
1098 * @category Components
1099 * @mode framework
1100 * @param props Props
1101 * @param props.page The absolute path of the page to prefetch, e.g. `/absolute/path`.
1102 * @param props.linkProps Additional props to spread onto the
1103 * [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/link)
1104 * tags, such as `crossOrigin`, `integrity`, `rel`, etc.
1105 * @returns A collection of React elements for `<link>` tags
1106 */
1107declare function PrefetchPageLinks({ page, ...linkProps }: PageLinkDescriptor): React.JSX.Element | null;
1108/**
1109 * Renders all the `<meta>` tags created by the route module
1110 * [`meta`](../../start/framework/route-module#meta) exports. You should render
1111 * it inside the `<head>` of your HTML.
1112 *
1113 * @example
1114 * import { Meta } from "react-router";
1115 *
1116 * export default function Root() {
1117 * return (
1118 * <html>
1119 * <head>
1120 * <Meta />
1121 * </head>
1122 * </html>
1123 * );
1124 * }
1125 *
1126 * @public
1127 * @category Components
1128 * @mode framework
1129 * @returns A collection of React elements for `<meta>` tags
1130 */
1131declare function Meta(): React.JSX.Element;
1132/**
1133 * A couple common attributes:
1134 *
1135 * - `<Scripts crossOrigin>` for hosting your static assets on a different server than your app.
1136 * - `<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) with [nonce-sources](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/Sources#sources) for your `<script>` tags.
1137 *
1138 * You cannot pass through attributes such as `async`, `defer`, `src`, `type`, `noModule` because they are managed by React Router internally.
1139 *
1140 * @category Types
1141 */
1142type ScriptsProps = Omit<React.HTMLProps<HTMLScriptElement>, "async" | "children" | "dangerouslySetInnerHTML" | "defer" | "src" | "type" | "noModule" | "suppressHydrationWarning"> & {
1143 /**
1144 * A [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
1145 * attribute to render on [the `<script>` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script)
1146 */
1147 nonce?: string | undefined;
1148};
1149/**
1150 * Renders the client runtime of your app. It should be rendered inside the
1151 * [`<body>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/body)
1152 * of the document.
1153 *
1154 * If server rendering, you can omit `<Scripts/>` and the app will work as a
1155 * traditional web app without JavaScript, relying solely on HTML and browser
1156 * behaviors.
1157 *
1158 * @example
1159 * import { Scripts } from "react-router";
1160 *
1161 * export default function Root() {
1162 * return (
1163 * <html>
1164 * <head />
1165 * <body>
1166 * <Scripts />
1167 * </body>
1168 * </html>
1169 * );
1170 * }
1171 *
1172 * @public
1173 * @category Components
1174 * @mode framework
1175 * @param scriptProps Additional props to spread onto the
1176 * [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script)
1177 * tag, such as `crossOrigin`, `nonce`, etc.
1178 * @returns A collection of React elements for `<script>` tags
1179 */
1180declare function Scripts(scriptProps: ScriptsProps): React.JSX.Element | null;
1181
1182/**
1183 * @category Data Routers
1184 */
1185interface DOMRouterOpts {
1186 /**
1187 * Basename path for the application.
1188 */
1189 basename?: string;
1190 /**
1191 * Function to provide the initial `context` values for all client side navigations/fetches
1192 */
1193 unstable_getContext?: RouterInit["unstable_getContext"];
1194 /**
1195 * Future flags to enable for the router.
1196 */
1197 future?: Partial<FutureConfig$1>;
1198 /**
1199 * When Server-Rendering and opting-out of automatic hydration, the `hydrationData`
1200 * option allows you to pass in hydration data from your server-render. This will
1201 * almost always be a subset of data from the {@link StaticHandlerContext} value you
1202 * get back from the `{@link StaticHandler} `query()` method:
1203 *
1204 * ```tsx
1205 * const router = createBrowserRouter(routes, {
1206 * hydrationData: {
1207 * loaderData: {
1208 * // [routeId]: serverLoaderData
1209 * },
1210 * // may also include `errors` and/or `actionData`
1211 * },
1212 * });
1213 * ```
1214 *
1215 * **Partial Hydration Data**
1216 *
1217 * You will almost always include a complete set of `loaderData` to hydrate a
1218 * server-rendered app. But in advanced use-cases (such as Framework Mode's
1219 * `clientLoader`), you may want to include `loaderData` for only some routes
1220 * that were loaded/rendered on the server. This allows you to hydrate _some_
1221 * of the routes (such as the app layout/shell) while showing a `HydrateFallback`
1222 * and running the loaders for other routes during hydration.
1223 *
1224 * A route `loader` will run during hydration in 2 scenarios:
1225 *
1226 * - No hydration data is provided
1227 * - In these cases the `HydrateFallback` component will render on initial hydration
1228 * - The `loader.hydrate` property is set to true
1229 * - This allows you to run the loader even if you did not render a fallback
1230 * on initial hydration (i.e., to prime a cache with hydration data)
1231 *
1232 * ```tsx
1233 * const router = createBrowserRouter(
1234 * [
1235 * {
1236 * id: "root",
1237 * loader: rootLoader,
1238 * Component: Root,
1239 * children: [
1240 * {
1241 * id: "index",
1242 * loader: indexLoader,
1243 * HydrateFallback: IndexSkeleton,
1244 * Component: Index,
1245 * },
1246 * ],
1247 * },
1248 * ],
1249 * {
1250 * hydrationData: {
1251 * loaderData: {
1252 * root: "ROOT DATA",
1253 * // No index data provided
1254 * },
1255 * },
1256 * }
1257 * );
1258 * ```
1259 */
1260 hydrationData?: HydrationState;
1261 /**
1262 * Override the default data strategy of running loaders in parallel.
1263 * See {@link DataStrategyFunction}.
1264 *
1265 * <docs-warning>This is a low-level API intended for advanced use-cases. This
1266 * overrides React Router's internal handling of `loader`/`action` execution,
1267 * and if done incorrectly will break your app code. Please use with caution
1268 * and perform the appropriate testing.</docs-warning>
1269 *
1270 * By default, React Router is opinionated about how your data is loaded/submitted -
1271 * and most notably, executes all of your loaders in parallel for optimal data
1272 * fetching. While we think this is the right behavior for most use-cases, we
1273 * realize that there is no "one size fits all" solution when it comes to data
1274 * fetching for the wide landscape of application requirements.
1275 *
1276 * The `dataStrategy` option gives you full control over how your loaders and
1277 * actions are executed and lays the foundation to build in more advanced APIs
1278 * such as middleware, context, and caching layers. Over time, we expect that
1279 * we'll leverage this API internally to bring more first class APIs to React
1280 * Router, but until then (and beyond), this is your way to add more advanced
1281 * functionality for your applications data needs.
1282 *
1283 * The `dataStrategy` function should return a key/value object of
1284 * `routeId` -> {@link DataStrategyResult} and should include entries for any routes
1285 * where a handler was executed. A `DataStrategyResult` indicates if the handler
1286 * was successful or not based on the `DataStrategyResult.type` field. If the
1287 * returned `DataStrategyResult["result"]` is a `Response`, React Router will
1288 * unwrap it for you (via `res.json` or `res.text`). If you need to do custom
1289 * decoding of a `Response` but want to preserve the status code, you can use
1290 * the `data` utility to return your decoded data along with a `ResponseInit`.
1291 *
1292 * <details>
1293 * <summary><b>Example <code>dataStrategy</code> Use Cases</b></summary>
1294 *
1295 * **Adding logging**
1296 *
1297 * In the simplest case, let's look at hooking into this API to add some logging
1298 * for when our route loaders/actions execute:
1299 *
1300 * ```ts
1301 * let router = createBrowserRouter(routes, {
1302 * async dataStrategy({ request, matches }) {
1303 * const matchesToLoad = matches.filter((m) => m.shouldLoad);
1304 * const results = {};
1305 * await Promise.all(
1306 * matchesToLoad.map(async (match) => {
1307 * console.log(`Processing ${match.route.id}`);
1308 * results[match.route.id] = await match.resolve();;
1309 * })
1310 * );
1311 * return results;
1312 * },
1313 * });
1314 * ```
1315 *
1316 * **Middleware**
1317 *
1318 * Let's define a middleware on each route via `handle` and call middleware
1319 * sequentially first, then call all loaders in parallel - providing any data
1320 * made available via the middleware:
1321 *
1322 * ```ts
1323 * const routes = [
1324 * {
1325 * id: "parent",
1326 * path: "/parent",
1327 * loader({ request }, context) {
1328 * // ...
1329 * },
1330 * handle: {
1331 * async middleware({ request }, context) {
1332 * context.parent = "PARENT MIDDLEWARE";
1333 * },
1334 * },
1335 * children: [
1336 * {
1337 * id: "child",
1338 * path: "child",
1339 * loader({ request }, context) {
1340 * // ...
1341 * },
1342 * handle: {
1343 * async middleware({ request }, context) {
1344 * context.child = "CHILD MIDDLEWARE";
1345 * },
1346 * },
1347 * },
1348 * ],
1349 * },
1350 * ];
1351 *
1352 * let router = createBrowserRouter(routes, {
1353 * async dataStrategy({ request, params, matches }) {
1354 * // Run middleware sequentially and let them add data to `context`
1355 * let context = {};
1356 * for (const match of matches) {
1357 * if (match.route.handle?.middleware) {
1358 * await match.route.handle.middleware(
1359 * { request, params },
1360 * context
1361 * );
1362 * }
1363 * }
1364 *
1365 * // Run loaders in parallel with the `context` value
1366 * let matchesToLoad = matches.filter((m) => m.shouldLoad);
1367 * let results = await Promise.all(
1368 * matchesToLoad.map((match, i) =>
1369 * match.resolve((handler) => {
1370 * // Whatever you pass to `handler` will be passed as the 2nd parameter
1371 * // to your loader/action
1372 * return handler(context);
1373 * })
1374 * )
1375 * );
1376 * return results.reduce(
1377 * (acc, result, i) =>
1378 * Object.assign(acc, {
1379 * [matchesToLoad[i].route.id]: result,
1380 * }),
1381 * {}
1382 * );
1383 * },
1384 * });
1385 * ```
1386 *
1387 * **Custom Handler**
1388 *
1389 * It's also possible you don't even want to define a loader implementation at
1390 * the route level. Maybe you want to just determine the routes and issue a single
1391 * GraphQL request for all of your data? You can do that by setting your
1392 * `route.loader=true` so it qualifies as "having a loader", and then store GQL
1393 * fragments on `route.handle`:
1394 *
1395 * ```ts
1396 * const routes = [
1397 * {
1398 * id: "parent",
1399 * path: "/parent",
1400 * loader: true,
1401 * handle: {
1402 * gql: gql`
1403 * fragment Parent on Whatever {
1404 * parentField
1405 * }
1406 * `,
1407 * },
1408 * children: [
1409 * {
1410 * id: "child",
1411 * path: "child",
1412 * loader: true,
1413 * handle: {
1414 * gql: gql`
1415 * fragment Child on Whatever {
1416 * childField
1417 * }
1418 * `,
1419 * },
1420 * },
1421 * ],
1422 * },
1423 * ];
1424 *
1425 * let router = createBrowserRouter(routes, {
1426 * async dataStrategy({ request, params, matches }) {
1427 * // Compose route fragments into a single GQL payload
1428 * let gql = getFragmentsFromRouteHandles(matches);
1429 * let data = await fetchGql(gql);
1430 * // Parse results back out into individual route level `DataStrategyResult`'s
1431 * // keyed by `routeId`
1432 * let results = parseResultsFromGql(data);
1433 * return results;
1434 * },
1435 * });
1436 * ```
1437 *</details>
1438 */
1439 dataStrategy?: DataStrategyFunction;
1440 /**
1441 * Lazily define portions of the route tree on navigations.
1442 * See {@link PatchRoutesOnNavigationFunction}.
1443 *
1444 * By default, React Router wants you to provide a full route tree up front via
1445 * `createBrowserRouter(routes)`. This allows React Router to perform synchronous
1446 * route matching, execute loaders, and then render route components in the most
1447 * optimistic manner without introducing waterfalls. The tradeoff is that your
1448 * initial JS bundle is larger by definition - which may slow down application
1449 * start-up times as your application grows.
1450 *
1451 * To combat this, we introduced [`route.lazy`][route-lazy] in [v6.9.0][6-9-0]
1452 * which let's you lazily load the route _implementation_ (`loader`, `Component`,
1453 * etc.) while still providing the route _definition_ aspects up front (`path`,
1454 * `index`, etc.). This is a good middle ground because React Router still knows
1455 * about your route definitions (the lightweight part) up front and can perform
1456 * synchronous route matching, but then delay loading any of the route implementation
1457 * aspects (the heavier part) until the route is actually navigated to.
1458 *
1459 * In some cases, even this doesn't go far enough. For very large applications,
1460 * providing all route definitions up front can be prohibitively expensive.
1461 * Additionally, it might not even be possible to provide all route definitions
1462 * up front in certain Micro-Frontend or Module-Federation architectures.
1463 *
1464 * This is where `patchRoutesOnNavigation` comes in ([RFC][fog-of-war-rfc]).
1465 * This API is for advanced use-cases where you are unable to provide the full
1466 * route tree up-front and need a way to lazily "discover" portions of the route
1467 * tree at runtime. This feature is often referred to as ["Fog of War"][fog-of-war]
1468 * because similar to how video games expand the "world" as you move around -
1469 * the router would be expanding its routing tree as the user navigated around
1470 * the app - but would only ever end up loading portions of the tree that the
1471 * user visited.
1472 *
1473 * `patchRoutesOnNavigation` will be called anytime React Router is unable to
1474 * match a `path`. The arguments include the `path`, any partial `matches`, and
1475 * a `patch` function you can call to patch new routes into the tree at a
1476 * specific location. This method is executed during the `loading` portion of
1477 * the navigation for `GET` requests and during the `submitting` portion of the
1478 * navigation for non-`GET` requests.
1479 *
1480 * <details>
1481 * <summary><b>Example <code>patchRoutesOnNavigation</code> Use Cases</b></summary>
1482 *
1483 * **Patching children into an existing route**
1484 *
1485 * ```tsx
1486 * const router = createBrowserRouter(
1487 * [
1488 * {
1489 * id: "root",
1490 * path: "/",
1491 * Component: RootComponent,
1492 * },
1493 * ],
1494 * {
1495 * async patchRoutesOnNavigation({ path, patch }) {
1496 * if (path === "/a") {
1497 * // Load/patch the `a` route as a child of the route with id `root`
1498 * let route = await getARoute();
1499 * // ^ { path: 'a', Component: A }
1500 * patch("root", [route]);
1501 * }
1502 * },
1503 * }
1504 * );
1505 * ```
1506 *
1507 * In the above example, if the user clicks a link to `/a`, React Router won't
1508 * match any routes initially and will call `patchRoutesOnNavigation` with a
1509 * `path = "/a"` and a `matches` array containing the root route match. By calling
1510 * `patch('root', [route])`, the new route will be added to the route tree as a
1511 * child of the `root` route and React Router will perform matching on the updated
1512 * routes. This time it will successfully match the `/a` path and the navigation
1513 * will complete successfully.
1514 *
1515 * **Patching new root-level routes**
1516 *
1517 * If you need to patch a new route to the top of the tree (i.e., it doesn't
1518 * have a parent), you can pass `null` as the `routeId`:
1519 *
1520 * ```tsx
1521 * const router = createBrowserRouter(
1522 * [
1523 * {
1524 * id: "root",
1525 * path: "/",
1526 * Component: RootComponent,
1527 * },
1528 * ],
1529 * {
1530 * async patchRoutesOnNavigation({ path, patch }) {
1531 * if (path === "/root-sibling") {
1532 * // Load/patch the `/root-sibling` route as a sibling of the root route
1533 * let route = await getRootSiblingRoute();
1534 * // ^ { path: '/root-sibling', Component: RootSibling }
1535 * patch(null, [route]);
1536 * }
1537 * },
1538 * }
1539 * );
1540 * ```
1541 *
1542 * **Patching sub-trees asynchronously**
1543 *
1544 * You can also perform asynchronous matching to lazily fetch entire sections
1545 * of your application:
1546 *
1547 * ```jsx
1548 * let router = createBrowserRouter(
1549 * [
1550 * {
1551 * path: "/",
1552 * Component: Home,
1553 * },
1554 * ],
1555 * {
1556 * async patchRoutesOnNavigation({ path, patch }) {
1557 * if (path.startsWith("/dashboard")) {
1558 * let children = await import("./dashboard");
1559 * patch(null, children);
1560 * }
1561 * if (path.startsWith("/account")) {
1562 * let children = await import("./account");
1563 * patch(null, children);
1564 * }
1565 * },
1566 * }
1567 * );
1568 * ```
1569 *
1570 * <docs-info>If in-progress execution of `patchRoutesOnNavigation` is
1571 * interrupted by a subsequent navigation, then any remaining `patch` calls
1572 * in the interrupted execution will not update the route tree because the
1573 * operation was cancelled.</docs-info>
1574 *
1575 * **Co-locating route discovery with route definition**
1576 *
1577 * If you don't wish to perform your own pseudo-matching, you can leverage the
1578 * partial `matches` array and the `handle` field on a route to keep the children
1579 * definitions co-located:
1580 *
1581 * ```jsx
1582 * let router = createBrowserRouter(
1583 * [
1584 * {
1585 * path: "/",
1586 * Component: Home,
1587 * },
1588 * {
1589 * path: "/dashboard",
1590 * children: [
1591 * {
1592 * // If we want to include /dashboard in the critical routes, we need to
1593 * // also include it's index route since patchRoutesOnNavigation will not be
1594 * // called on a navigation to `/dashboard` because it will have successfully
1595 * // matched the `/dashboard` parent route
1596 * index: true,
1597 * // ...
1598 * },
1599 * ],
1600 * handle: {
1601 * lazyChildren: () => import("./dashboard"),
1602 * },
1603 * },
1604 * {
1605 * path: "/account",
1606 * children: [
1607 * {
1608 * index: true,
1609 * // ...
1610 * },
1611 * ],
1612 * handle: {
1613 * lazyChildren: () => import("./account"),
1614 * },
1615 * },
1616 * ],
1617 * {
1618 * async patchRoutesOnNavigation({ matches, patch }) {
1619 * let leafRoute = matches[matches.length - 1]?.route;
1620 * if (leafRoute?.handle?.lazyChildren) {
1621 * let children =
1622 * await leafRoute.handle.lazyChildren();
1623 * patch(leafRoute.id, children);
1624 * }
1625 * },
1626 * }
1627 * );
1628 * ```
1629 *
1630 * **A note on routes with parameters**
1631 *
1632 * Because React Router uses ranked routes to find the best match for a given
1633 * path, there is an interesting ambiguity introduced when only a partial route
1634 * tree is known at any given point in time. If we match a fully static route
1635 * such as `path: "/about/contact-us"` then we know we've found the right match
1636 * since it's composed entirely of static URL segments, and thus we do not need
1637 * to bother asking for any other potentially higher-scoring routes.
1638 *
1639 * However, routes with parameters (dynamic or splat) can't make this assumption
1640 * because there might be a not-yet-discovered route tht scores higher. Consider
1641 * a full route tree such as:
1642 *
1643 * ```js
1644 * // Assume this is the full route tree for your app
1645 * const routes = [
1646 * {
1647 * path: "/",
1648 * Component: Home,
1649 * },
1650 * {
1651 * id: "blog",
1652 * path: "/blog",
1653 * Component: BlogLayout,
1654 * children: [
1655 * { path: "new", Component: NewPost },
1656 * { path: ":slug", Component: BlogPost },
1657 * ],
1658 * },
1659 * ];
1660 * ```
1661 *
1662 * And then assume we want to use `patchRoutesOnNavigation` to fill this in
1663 * as the user navigates around:
1664 *
1665 * ```js
1666 * // Start with only the index route
1667 * const router = createBrowserRouter(
1668 * [
1669 * {
1670 * path: "/",
1671 * Component: Home,
1672 * },
1673 * ],
1674 * {
1675 * patchRoutesOnNavigation({ path, patch }) {
1676 * if (path === "/blog/new") {
1677 * patch("blog", [
1678 * {
1679 * path: "new",
1680 * Component: NewPost,
1681 * },
1682 * ]);
1683 * } else if (path.startsWith("/blog")) {
1684 * patch("blog", [
1685 * {
1686 * path: ":slug",
1687 * Component: BlogPost,
1688 * },
1689 * ]);
1690 * }
1691 * },
1692 * }
1693 * );
1694 * ```
1695 *
1696 * If the user were to a blog post first (i.e., `/blog/my-post`) we would patch
1697 * in the `:slug` route. Then if the user navigated to `/blog/new` to write a
1698 * new post, we'd match `/blog/:slug` but it wouldn't be the _right_ match!
1699 * We need to call `patchRoutesOnNavigation` just in case there exists a
1700 * higher-scoring route we've not yet discovered, which in this case there is.
1701 *
1702 * So, anytime React Router matches a path that contains at least one param,
1703 * it will call `patchRoutesOnNavigation` and match routes again just to
1704 * confirm it has found the best match.
1705 *
1706 * If your `patchRoutesOnNavigation` implementation is expensive or making
1707 * side-effect `fetch` calls to a backend server, you may want to consider
1708 * tracking previously seen routes to avoid over-fetching in cases where you
1709 * know the proper route has already been found. This can usually be as simple
1710 * as maintaining a small cache of prior `path` values for which you've already
1711 * patched in the right routes:
1712 *
1713 * ```js
1714 * let discoveredRoutes = new Set();
1715 *
1716 * const router = createBrowserRouter(routes, {
1717 * patchRoutesOnNavigation({ path, patch }) {
1718 * if (discoveredRoutes.has(path)) {
1719 * // We've seen this before so nothing to patch in and we can let the router
1720 * // use the routes it already knows about
1721 * return;
1722 * }
1723 *
1724 * discoveredRoutes.add(path);
1725 *
1726 * // ... patch routes in accordingly
1727 * },
1728 * });
1729 * ```
1730 * </details>
1731 */
1732 patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;
1733 /**
1734 * [`Window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) object
1735 * override - defaults to the global `window` instance.
1736 */
1737 window?: Window;
1738}
1739/**
1740 * Create a new {@link DataRouter| data router} that manages the application
1741 * path via [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)
1742 * and [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState).
1743 *
1744 * @public
1745 * @category Data Routers
1746 * @mode data
1747 * @param routes Application routes
1748 * @param opts Options
1749 * @param {DOMRouterOpts.basename} opts.basename n/a
1750 * @param {DOMRouterOpts.dataStrategy} opts.dataStrategy n/a
1751 * @param {DOMRouterOpts.future} opts.future n/a
1752 * @param {DOMRouterOpts.unstable_getContext} opts.unstable_getContext n/a
1753 * @param {DOMRouterOpts.hydrationData} opts.hydrationData n/a
1754 * @param {DOMRouterOpts.patchRoutesOnNavigation} opts.patchRoutesOnNavigation n/a
1755 * @param {DOMRouterOpts.window} opts.window n/a
1756 * @returns An initialized {@link DataRouter| data router} to pass to {@link RouterProvider | `<RouterProvider>`}
1757 */
1758declare function createBrowserRouter(routes: RouteObject[], opts?: DOMRouterOpts): Router$1;
1759/**
1760 * Create a new {@link DataRouter| data router} that manages the application
1761 * path via the URL [`hash`]https://developer.mozilla.org/en-US/docs/Web/API/URL/hash).
1762 *
1763 * @public
1764 * @category Data Routers
1765 * @mode data
1766 * @param routes Application routes
1767 * @param opts Options
1768 * @param {DOMRouterOpts.basename} opts.basename n/a
1769 * @param {DOMRouterOpts.future} opts.future n/a
1770 * @param {DOMRouterOpts.unstable_getContext} opts.unstable_getContext n/a
1771 * @param {DOMRouterOpts.hydrationData} opts.hydrationData n/a
1772 * @param {DOMRouterOpts.dataStrategy} opts.dataStrategy n/a
1773 * @param {DOMRouterOpts.patchRoutesOnNavigation} opts.patchRoutesOnNavigation n/a
1774 * @param {DOMRouterOpts.window} opts.window n/a
1775 * @returns An initialized {@link DataRouter| data router} to pass to {@link RouterProvider | `<RouterProvider>`}
1776 */
1777declare function createHashRouter(routes: RouteObject[], opts?: DOMRouterOpts): Router$1;
1778/**
1779 * @category Types
1780 */
1781interface BrowserRouterProps {
1782 basename?: string;
1783 children?: React.ReactNode;
1784 window?: Window;
1785}
1786/**
1787 * A declarative {@link Router | `<Router>`} using the browser [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
1788 * API for client-side routing.
1789 *
1790 * @public
1791 * @category Declarative Routers
1792 * @mode declarative
1793 * @param props Props
1794 * @param props.basename Application basename
1795 * @param props.children {@link Route | `<Route>`} components describing your route configuration
1796 * @param props.window [`Window`](https://developer.mozilla.org/en-US/docs/Web/API/Window)
1797 * object override - defaults to the global `window` instance
1798 * @returns A declarative {@link Router | `<Router>`} using the browser [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
1799 * API for client-side routing.
1800 */
1801declare function BrowserRouter({ basename, children, window, }: BrowserRouterProps): React.JSX.Element;
1802/**
1803 * @category Types
1804 */
1805interface HashRouterProps {
1806 basename?: string;
1807 children?: React.ReactNode;
1808 window?: Window;
1809}
1810/**
1811 * A declarative {@link Router | `<Router>`} that stores the location in the
1812 * [`hash`](https://developer.mozilla.org/en-US/docs/Web/API/URL/hash) portion
1813 * of the URL so it is not sent to the server.
1814 *
1815 * @public
1816 * @category Declarative Routers
1817 * @mode declarative
1818 * @param props Props
1819 * @param props.basename Application basename
1820 * @param props.children {@link Route | `<Route>`} components describing your route configuration
1821 * @param props.window [`Window`](https://developer.mozilla.org/en-US/docs/Web/API/Window)
1822 * object override - defaults to the global `window` instance
1823 * @returns A declarative {@link Router | `<Router>`} using the URL [`hash`](https://developer.mozilla.org/en-US/docs/Web/API/URL/hash)
1824 * for client-side routing.
1825 */
1826declare function HashRouter({ basename, children, window }: HashRouterProps): React.JSX.Element;
1827/**
1828 * @category Types
1829 */
1830interface HistoryRouterProps {
1831 basename?: string;
1832 children?: React.ReactNode;
1833 history: History;
1834}
1835/**
1836 * A declarative {@link Router | `<Router>`} that accepts a pre-instantiated
1837 * `history` object.
1838 * It's important to note that using your own `history` object is highly discouraged
1839 * and may add two versions of the `history` library to your bundles unless you use
1840 * the same version of the `history` library that React Router uses internally.
1841 *
1842 * @name unstable_HistoryRouter
1843 * @public
1844 * @category Declarative Routers
1845 * @mode declarative
1846 * @param props Props
1847 * @param props.basename Application basename
1848 * @param props.children {@link Route | `<Route>`} components describing your route configuration
1849 * @param props.history A history implementation for use by the router
1850 * @returns A declarative router using the provided history implementation for client-side routing.
1851 */
1852declare function HistoryRouter({ basename, children, history, }: HistoryRouterProps): React.JSX.Element;
1853declare namespace HistoryRouter {
1854 var displayName: string;
1855}
1856/**
1857 * @category Types
1858 */
1859interface LinkProps extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href"> {
1860 /**
1861 * Defines the link discovery behavior
1862 *
1863 * ```tsx
1864 * <Link /> // default ("render")
1865 * <Link discover="render" />
1866 * <Link discover="none" />
1867 * ```
1868 *
1869 * - **render** - default, discover the route when the link renders
1870 * - **none** - don't eagerly discover, only discover if the link is clicked
1871 */
1872 discover?: DiscoverBehavior;
1873 /**
1874 * Defines the data and module prefetching behavior for the link.
1875 *
1876 * ```tsx
1877 * <Link /> // default
1878 * <Link prefetch="none" />
1879 * <Link prefetch="intent" />
1880 * <Link prefetch="render" />
1881 * <Link prefetch="viewport" />
1882 * ```
1883 *
1884 * - **none** - default, no prefetching
1885 * - **intent** - prefetches when the user hovers or focuses the link
1886 * - **render** - prefetches when the link renders
1887 * - **viewport** - prefetches when the link is in the viewport, very useful for mobile
1888 *
1889 * Prefetching is done with HTML [`<link rel="prefetch">`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
1890 * tags. They are inserted after the link.
1891 *
1892 * ```tsx
1893 * <a href="..." />
1894 * <a href="..." />
1895 * <link rel="prefetch" /> // might conditionally render
1896 * ```
1897 *
1898 * Because of this, if you are using `nav :last-child` you will need to use
1899 * `nav :last-of-type` so the styles don't conditionally fall off your last link
1900 * (and any other similar selectors).
1901 */
1902 prefetch?: PrefetchBehavior;
1903 /**
1904 * Will use document navigation instead of client side routing when the link is
1905 * clicked: the browser will handle the transition normally (as if it were an
1906 * [`<a href>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a)).
1907 *
1908 * ```tsx
1909 * <Link to="/logout" reloadDocument />
1910 * ```
1911 */
1912 reloadDocument?: boolean;
1913 /**
1914 * Replaces the current entry in the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
1915 * stack instead of pushing a new one onto it.
1916 *
1917 * ```tsx
1918 * <Link replace />
1919 * ```
1920 *
1921 * ```
1922 * # with a history stack like this
1923 * A -> B
1924 *
1925 * # normal link click pushes a new entry
1926 * A -> B -> C
1927 *
1928 * # but with `replace`, B is replaced by C
1929 * A -> C
1930 * ```
1931 */
1932 replace?: boolean;
1933 /**
1934 * Adds persistent client side routing state to the next location.
1935 *
1936 * ```tsx
1937 * <Link to="/somewhere/else" state={{ some: "value" }} />
1938 * ```
1939 *
1940 * The location state is accessed from the `location`.
1941 *
1942 * ```tsx
1943 * function SomeComp() {
1944 * const location = useLocation();
1945 * location.state; // { some: "value" }
1946 * }
1947 * ```
1948 *
1949 * This state is inaccessible on the server as it is implemented on top of
1950 * [`history.state`](https://developer.mozilla.org/en-US/docs/Web/API/History/state)
1951 */
1952 state?: any;
1953 /**
1954 * Prevents the scroll position from being reset to the top of the window when
1955 * the link is clicked and the app is using {@link ScrollRestoration}. This only
1956 * prevents new locations resetting scroll to the top, scroll position will be
1957 * restored for back/forward button navigation.
1958 *
1959 * ```tsx
1960 * <Link to="?tab=one" preventScrollReset />
1961 * ```
1962 */
1963 preventScrollReset?: boolean;
1964 /**
1965 * Defines the relative path behavior for the link.
1966 *
1967 * ```tsx
1968 * <Link to=".." /> // default: "route"
1969 * <Link relative="route" />
1970 * <Link relative="path" />
1971 * ```
1972 *
1973 * Consider a route hierarchy where a parent route pattern is `"blog"` and a child
1974 * route pattern is `"blog/:slug/edit"`.
1975 *
1976 * - **route** - default, resolves the link relative to the route pattern. In the
1977 * example above, a relative link of `".."` will remove both `:slug/edit` segments
1978 * back to `"/blog"`.
1979 * - **path** - relative to the path so `".."` will only remove one URL segment up
1980 * to `"/blog/:slug"`
1981 *
1982 * Note that index routes and layout routes do not have paths so they are not
1983 * included in the relative path calculation.
1984 */
1985 relative?: RelativeRoutingType;
1986 /**
1987 * Can be a string or a partial {@link Path}:
1988 *
1989 * ```tsx
1990 * <Link to="/some/path" />
1991 *
1992 * <Link
1993 * to={{
1994 * pathname: "/some/path",
1995 * search: "?query=string",
1996 * hash: "#hash",
1997 * }}
1998 * />
1999 * ```
2000 */
2001 to: To;
2002 /**
2003 * Enables a [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API)
2004 * for this navigation.
2005 *
2006 * ```jsx
2007 * <Link to={to} viewTransition>
2008 * Click me
2009 * </Link>
2010 * ```
2011 *
2012 * To apply specific styles for the transition, see {@link useViewTransitionState}
2013 */
2014 viewTransition?: boolean;
2015}
2016/**
2017 * A progressively enhanced [`<a href>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a)
2018 * wrapper to enable navigation with client-side routing.
2019 *
2020 * @example
2021 * import { Link } from "react-router";
2022 *
2023 * <Link to="/dashboard">Dashboard</Link>;
2024 *
2025 * <Link
2026 * to={{
2027 * pathname: "/some/path",
2028 * search: "?query=string",
2029 * hash: "#hash",
2030 * }}
2031 * />;
2032 *
2033 * @public
2034 * @category Components
2035 * @param {LinkProps.discover} props.discover [modes: framework] n/a
2036 * @param {LinkProps.prefetch} props.prefetch [modes: framework] n/a
2037 * @param {LinkProps.preventScrollReset} props.preventScrollReset [modes: framework, data] n/a
2038 * @param {LinkProps.relative} props.relative n/a
2039 * @param {LinkProps.reloadDocument} props.reloadDocument n/a
2040 * @param {LinkProps.replace} props.replace n/a
2041 * @param {LinkProps.state} props.state n/a
2042 * @param {LinkProps.to} props.to n/a
2043 * @param {LinkProps.viewTransition} props.viewTransition [modes: framework, data] n/a
2044 */
2045declare const Link: React.ForwardRefExoticComponent<LinkProps & React.RefAttributes<HTMLAnchorElement>>;
2046/**
2047 * The object passed to {@link NavLink} `children`, `className`, and `style` prop
2048 * callbacks to render and style the link based on its state.
2049 *
2050 * ```
2051 * // className
2052 * <NavLink
2053 * to="/messages"
2054 * className={({ isActive, isPending }) =>
2055 * isPending ? "pending" : isActive ? "active" : ""
2056 * }
2057 * >
2058 * Messages
2059 * </NavLink>
2060 *
2061 * // style
2062 * <NavLink
2063 * to="/messages"
2064 * style={({ isActive, isPending }) => {
2065 * return {
2066 * fontWeight: isActive ? "bold" : "",
2067 * color: isPending ? "red" : "black",
2068 * }
2069 * )}
2070 * />
2071 *
2072 * // children
2073 * <NavLink to="/tasks">
2074 * {({ isActive, isPending }) => (
2075 * <span className={isActive ? "active" : ""}>Tasks</span>
2076 * )}
2077 * </NavLink>
2078 * ```
2079 *
2080 */
2081type NavLinkRenderProps = {
2082 /**
2083 * Indicates if the link's URL matches the current {@link Location}.
2084 */
2085 isActive: boolean;
2086 /**
2087 * Indicates if the pending {@link Location} matches the link's URL. Only
2088 * available in Framework/Data modes.
2089 */
2090 isPending: boolean;
2091 /**
2092 * Indicates if a view transition to the link's URL is in progress.
2093 * See {@link useViewTransitionState}
2094 */
2095 isTransitioning: boolean;
2096};
2097/**
2098 * @category Types
2099 */
2100interface NavLinkProps extends Omit<LinkProps, "className" | "style" | "children"> {
2101 /**
2102 * Can be regular React children or a function that receives an object with the
2103 * `active` and `pending` states of the link.
2104 *
2105 * ```tsx
2106 * <NavLink to="/tasks">
2107 * {({ isActive }) => (
2108 * <span className={isActive ? "active" : ""}>Tasks</span>
2109 * )}
2110 * </NavLink>
2111 * ```
2112 */
2113 children?: React.ReactNode | ((props: NavLinkRenderProps) => React.ReactNode);
2114 /**
2115 * Changes the matching logic to make it case-sensitive:
2116 *
2117 * | Link | URL | isActive |
2118 * | -------------------------------------------- | ------------- | -------- |
2119 * | `<NavLink to="/SpOnGe-bOB" />` | `/sponge-bob` | true |
2120 * | `<NavLink to="/SpOnGe-bOB" caseSensitive />` | `/sponge-bob` | false |
2121 */
2122 caseSensitive?: boolean;
2123 /**
2124 * Classes are automatically applied to `NavLink` that correspond to the state.
2125 *
2126 * ```css
2127 * a.active {
2128 * color: red;
2129 * }
2130 * a.pending {
2131 * color: blue;
2132 * }
2133 * a.transitioning {
2134 * view-transition-name: my-transition;
2135 * }
2136 * ```
2137 *
2138 * Or you can specify a function that receives {@link NavLinkRenderProps} and
2139 * returns the `className`:
2140 *
2141 * ```tsx
2142 * <NavLink className={({ isActive, isPending }) => (
2143 * isActive ? "my-active-class" :
2144 * isPending ? "my-pending-class" :
2145 * ""
2146 * )} />
2147 * ```
2148 */
2149 className?: string | ((props: NavLinkRenderProps) => string | undefined);
2150 /**
2151 * Changes the matching logic for the `active` and `pending` states to only match
2152 * to the "end" of the {@link NavLinkProps.to}. If the URL is longer, it will no
2153 * longer be considered active.
2154 *
2155 * | Link | URL | isActive |
2156 * | ----------------------------- | ------------ | -------- |
2157 * | `<NavLink to="/tasks" />` | `/tasks` | true |
2158 * | `<NavLink to="/tasks" />` | `/tasks/123` | true |
2159 * | `<NavLink to="/tasks" end />` | `/tasks` | true |
2160 * | `<NavLink to="/tasks" end />` | `/tasks/123` | false |
2161 *
2162 * `<NavLink to="/">` is an exceptional case because _every_ URL matches `/`.
2163 * To avoid this matching every single route by default, it effectively ignores
2164 * the `end` prop and only matches when you're at the root route.
2165 */
2166 end?: boolean;
2167 /**
2168 * Styles can also be applied dynamically via a function that receives
2169 * {@link NavLinkRenderProps} and returns the styles:
2170 *
2171 * ```tsx
2172 * <NavLink to="/tasks" style={{ color: "red" }} />
2173 * <NavLink to="/tasks" style={({ isActive, isPending }) => ({
2174 * color:
2175 * isActive ? "red" :
2176 * isPending ? "blue" : "black"
2177 * })} />
2178 * ```
2179 */
2180 style?: React.CSSProperties | ((props: NavLinkRenderProps) => React.CSSProperties | undefined);
2181}
2182/**
2183 * Wraps {@link Link | `<Link>`} with additional props for styling active and
2184 * pending states.
2185 *
2186 * - Automatically applies classes to the link based on its `active` and `pending`
2187 * states, see {@link NavLinkProps.className}
2188 * - Note that `pending` is only available with Framework and Data modes.
2189 * - Automatically applies `aria-current="page"` to the link when the link is active.
2190 * See [`aria-current`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-current)
2191 * on MDN.
2192 * - States are additionally available through the className, style, and children
2193 * render props. See {@link NavLinkRenderProps}.
2194 *
2195 * @example
2196 * <NavLink to="/message">Messages</NavLink>
2197 *
2198 * // Using render props
2199 * <NavLink
2200 * to="/messages"
2201 * className={({ isActive, isPending }) =>
2202 * isPending ? "pending" : isActive ? "active" : ""
2203 * }
2204 * >
2205 * Messages
2206 * </NavLink>
2207 *
2208 * @public
2209 * @category Components
2210 * @param {NavLinkProps.caseSensitive} props.caseSensitive n/a
2211 * @param {NavLinkProps.children} props.children n/a
2212 * @param {NavLinkProps.className} props.className n/a
2213 * @param {NavLinkProps.discover} props.discover [modes: framework] n/a
2214 * @param {NavLinkProps.end} props.end n/a
2215 * @param {NavLinkProps.prefetch} props.prefetch [modes: framework] n/a
2216 * @param {NavLinkProps.preventScrollReset} props.preventScrollReset [modes: framework, data] n/a
2217 * @param {NavLinkProps.relative} props.relative n/a
2218 * @param {NavLinkProps.reloadDocument} props.reloadDocument n/a
2219 * @param {NavLinkProps.replace} props.replace n/a
2220 * @param {NavLinkProps.state} props.state n/a
2221 * @param {NavLinkProps.style} props.style n/a
2222 * @param {NavLinkProps.to} props.to n/a
2223 * @param {NavLinkProps.viewTransition} props.viewTransition [modes: framework, data] n/a
2224 */
2225declare const NavLink: React.ForwardRefExoticComponent<NavLinkProps & React.RefAttributes<HTMLAnchorElement>>;
2226/**
2227 * Form props shared by navigations and fetchers
2228 */
2229interface SharedFormProps extends React.FormHTMLAttributes<HTMLFormElement> {
2230 /**
2231 * The HTTP verb to use when the form is submitted. Supports "get", "post",
2232 * "put", "delete", and "patch".
2233 *
2234 * Native [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form)
2235 * only supports `get` and `post`, avoid the other verbs if you'd like to
2236 * support progressive enhancement
2237 */
2238 method?: HTMLFormMethod;
2239 /**
2240 * The encoding type to use for the form submission.
2241 *
2242 * ```tsx
2243 * <Form encType="application/x-www-form-urlencoded"/> // Default
2244 * <Form encType="multipart/form-data"/>
2245 * <Form encType="text/plain"/>
2246 * ```
2247 */
2248 encType?: "application/x-www-form-urlencoded" | "multipart/form-data" | "text/plain";
2249 /**
2250 * The URL to submit the form data to. If `undefined`, this defaults to the
2251 * closest route in context.
2252 */
2253 action?: string;
2254 /**
2255 * Determines whether the form action is relative to the route hierarchy or
2256 * the pathname. Use this if you want to opt out of navigating the route
2257 * hierarchy and want to instead route based on slash-delimited URL segments.
2258 * See {@link RelativeRoutingType}.
2259 */
2260 relative?: RelativeRoutingType;
2261 /**
2262 * Prevent the scroll position from resetting to the top of the viewport on
2263 * completion of the navigation when using the
2264 * {@link ScrollRestoration | `<ScrollRestoration>`} component
2265 */
2266 preventScrollReset?: boolean;
2267 /**
2268 * A function to call when the form is submitted. If you call
2269 * [`event.preventDefault()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
2270 * then this form will not do anything.
2271 */
2272 onSubmit?: React.FormEventHandler<HTMLFormElement>;
2273}
2274/**
2275 * Form props available to fetchers
2276 * @category Types
2277 */
2278interface FetcherFormProps extends SharedFormProps {
2279}
2280/**
2281 * Form props available to navigations
2282 * @category Types
2283 */
2284interface FormProps extends SharedFormProps {
2285 /**
2286 * Defines the link discovery behavior. See {@link DiscoverBehavior}.
2287 *
2288 * ```tsx
2289 * <Link /> // default ("render")
2290 * <Link discover="render" />
2291 * <Link discover="none" />
2292 * ```
2293 *
2294 * - **render** - default, discover the route when the link renders
2295 * - **none** - don't eagerly discover, only discover if the link is clicked
2296 */
2297 discover?: DiscoverBehavior;
2298 /**
2299 * Indicates a specific fetcherKey to use when using `navigate={false}` so you
2300 * can pick up the fetcher's state in a different component in a {@link useFetcher}.
2301 */
2302 fetcherKey?: string;
2303 /**
2304 * When `false`, skips the navigation and submits via a fetcher internally.
2305 * This is essentially a shorthand for {@link useFetcher} + `<fetcher.Form>` where
2306 * you don't care about the resulting data in this component.
2307 */
2308 navigate?: boolean;
2309 /**
2310 * Forces a full document navigation instead of client side routing and data
2311 * fetch.
2312 */
2313 reloadDocument?: boolean;
2314 /**
2315 * Replaces the current entry in the browser [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
2316 * stack when the form navigates. Use this if you don't want the user to be
2317 * able to click "back" to the page with the form on it.
2318 */
2319 replace?: boolean;
2320 /**
2321 * State object to add to the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
2322 * stack entry for this navigation
2323 */
2324 state?: any;
2325 /**
2326 * Enables a [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API)
2327 * for this navigation. To apply specific styles during the transition, see
2328 * {@link useViewTransitionState}.
2329 */
2330 viewTransition?: boolean;
2331}
2332/**
2333 * A progressively enhanced HTML [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form)
2334 * that submits data to actions via [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API),
2335 * activating pending states in {@link useNavigation} which enables advanced
2336 * user interfaces beyond a basic HTML [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form).
2337 * After a form's `action` completes, all data on the page is automatically
2338 * revalidated to keep the UI in sync with the data.
2339 *
2340 * Because it uses the HTML form API, server rendered pages are interactive at a
2341 * basic level before JavaScript loads. Instead of React Router managing the
2342 * submission, the browser manages the submission as well as the pending states
2343 * (like the spinning favicon). After JavaScript loads, React Router takes over
2344 * enabling web application user experiences.
2345 *
2346 * `Form` is most useful for submissions that should also change the URL or
2347 * otherwise add an entry to the browser history stack. For forms that shouldn't
2348 * manipulate the browser history stack, use [`<fetcher.Form>`][fetcher_form].
2349 *
2350 * @example
2351 * import { Form } from "react-router";
2352 *
2353 * function NewEvent() {
2354 * return (
2355 * <Form action="/events" method="post">
2356 * <input name="title" type="text" />
2357 * <input name="description" type="text" />
2358 * </Form>
2359 * );
2360 * }
2361 *
2362 * @public
2363 * @category Components
2364 * @mode framework
2365 * @mode data
2366 * @param {FormProps.action} action n/a
2367 * @param {FormProps.discover} discover n/a
2368 * @param {FormProps.encType} encType n/a
2369 * @param {FormProps.fetcherKey} fetcherKey n/a
2370 * @param {FormProps.method} method n/a
2371 * @param {FormProps.navigate} navigate n/a
2372 * @param {FormProps.onSubmit} onSubmit n/a
2373 * @param {FormProps.preventScrollReset} preventScrollReset n/a
2374 * @param {FormProps.relative} relative n/a
2375 * @param {FormProps.reloadDocument} reloadDocument n/a
2376 * @param {FormProps.replace} replace n/a
2377 * @param {FormProps.state} state n/a
2378 * @param {FormProps.viewTransition} viewTransition n/a
2379 * @returns A progressively enhanced [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) component
2380 */
2381declare const Form: React.ForwardRefExoticComponent<FormProps & React.RefAttributes<HTMLFormElement>>;
2382type ScrollRestorationProps = ScriptsProps & {
2383 /**
2384 * A function that returns a key to use for scroll restoration. This is useful
2385 * for custom scroll restoration logic, such as using only the pathname so
2386 * that subsequent navigations to prior paths will restore the scroll. Defaults
2387 * to `location.key`. See {@link GetScrollRestorationKeyFunction}.
2388 *
2389 * ```tsx
2390 * <ScrollRestoration
2391 * getKey={(location, matches) => {
2392 * // Restore based on a unique location key (default behavior)
2393 * return location.key
2394 *
2395 * // Restore based on pathname
2396 * return location.pathname
2397 * }}
2398 * />
2399 * ```
2400 */
2401 getKey?: GetScrollRestorationKeyFunction;
2402 /**
2403 * The key to use for storing scroll positions in [`sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage).
2404 * Defaults to `"react-router-scroll-positions"`.
2405 */
2406 storageKey?: string;
2407};
2408/**
2409 * Emulates the browser's scroll restoration on location changes. Apps should only render one of these, right before the {@link Scripts} component.
2410 *
2411 * ```tsx
2412 * import { ScrollRestoration } from "react-router";
2413 *
2414 * export default function Root() {
2415 * return (
2416 * <html>
2417 * <body>
2418 * <ScrollRestoration />
2419 * <Scripts />
2420 * </body>
2421 * </html>
2422 * );
2423 * }
2424 * ```
2425 *
2426 * 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.
2427 *
2428 * ```tsx
2429 * <ScrollRestoration nonce={cspNonce} />
2430 * ```
2431 *
2432 * @public
2433 * @category Components
2434 * @mode framework
2435 * @mode data
2436 * @param props Props
2437 * @param {ScrollRestorationProps.getKey} props.getKey n/a
2438 * @param {ScriptsProps.nonce} props.nonce n/a
2439 * @param {ScrollRestorationProps.storageKey} props.storageKey n/a
2440 * @returns A [`script`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)
2441 * tag that restores scroll positions on navigation.
2442 */
2443declare function ScrollRestoration({ getKey, storageKey, ...props }: ScrollRestorationProps): React.JSX.Element | null;
2444declare namespace ScrollRestoration {
2445 var displayName: string;
2446}
2447/**
2448 * Handles the click behavior for router {@link Link | `<Link>`} components.This
2449 * is useful if you need to create custom {@link Link | `<Link>`} components with
2450 * the same click behavior we use in our exported {@link Link | `<Link>`}.
2451 *
2452 * @public
2453 * @category Hooks
2454 * @param to The URL to navigate to, can be a string or a partial {@link Path}.
2455 * @param options Options
2456 * @param options.preventScrollReset Whether to prevent the scroll position from
2457 * being reset to the top of the viewport on completion of the navigation when
2458 * using the {@link ScrollRestoration} component. Defaults to `false`.
2459 * @param options.relative The {@link RelativeRoutingType | relative routing type}
2460 * to use for the link. Defaults to `"route"`.
2461 * @param options.replace Whether to replace the current [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
2462 * entry instead of pushing a new one. Defaults to `false`.
2463 * @param options.state The state to add to the [`History`](https://developer.mozilla.org/en-US/docs/Web/API/History)
2464 * entry for this navigation. Defaults to `undefined`.
2465 * @param options.target The target attribute for the link. Defaults to `undefined`.
2466 * @param options.viewTransition Enables a [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API)
2467 * for this navigation. To apply specific styles during the transition, see
2468 * {@link useViewTransitionState}. Defaults to `false`.
2469 * @returns A click handler function that can be used in a custom {@link Link} component.
2470 */
2471declare function useLinkClickHandler<E extends Element = HTMLAnchorElement>(to: To, { target, replace: replaceProp, state, preventScrollReset, relative, viewTransition, }?: {
2472 target?: React.HTMLAttributeAnchorTarget;
2473 replace?: boolean;
2474 state?: any;
2475 preventScrollReset?: boolean;
2476 relative?: RelativeRoutingType;
2477 viewTransition?: boolean;
2478}): (event: React.MouseEvent<E, MouseEvent>) => void;
2479/**
2480 * Returns a tuple of the current URL's [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
2481 * and a function to update them. Setting the search params causes a navigation.
2482 *
2483 * ```tsx
2484 * import { useSearchParams } from "react-router";
2485 *
2486 * export function SomeComponent() {
2487 * const [searchParams, setSearchParams] = useSearchParams();
2488 * // ...
2489 * }
2490 * ```
2491 *
2492 * ### `setSearchParams` function
2493 *
2494 * The second element of the tuple is a function that can be used to update the
2495 * search params. It accepts the same types as `defaultInit` and will
2496 * cause a navigation to the new URL.
2497 *
2498 * ```tsx
2499 * let [searchParams, setSearchParams] = useSearchParams();
2500 *
2501 * // a search param string
2502 * setSearchParams("?tab=1");
2503 *
2504 * // a shorthand object
2505 * setSearchParams({ tab: "1" });
2506 *
2507 * // object keys can be arrays for multiple values on the key
2508 * setSearchParams({ brand: ["nike", "reebok"] });
2509 *
2510 * // an array of tuples
2511 * setSearchParams([["tab", "1"]]);
2512 *
2513 * // a `URLSearchParams` object
2514 * setSearchParams(new URLSearchParams("?tab=1"));
2515 * ```
2516 *
2517 * It also supports a function callback like React's [`setState`](https://react.dev/reference/react/useState#setstate):
2518 *
2519 * ```tsx
2520 * setSearchParams((searchParams) => {
2521 * searchParams.set("tab", "2");
2522 * return searchParams;
2523 * });
2524 * ```
2525 *
2526 * ### Notes
2527 *
2528 * Note that `searchParams` is a stable reference, so you can reliably use it
2529 * as a dependency in React's [`useEffect`](https://react.dev/reference/react/useEffect)
2530 * hooks.
2531 *
2532 * ```tsx
2533 * useEffect(() => {
2534 * console.log(searchParams.get("tab"));
2535 * }, [searchParams]);
2536 * ```
2537 *
2538 * However, this also means it's mutable. If you change the object without
2539 * calling `setSearchParams`, its values will change between renders if some
2540 * other state causes the component to re-render and URL will not reflect the
2541 * values.
2542 *
2543 * @public
2544 * @category Hooks
2545 * @param defaultInit
2546 * You can initialize the search params with a default value, though it **will
2547 * not** change the URL on the first render.
2548 *
2549 * ```tsx
2550 * // a search param string
2551 * useSearchParams("?tab=1");
2552 *
2553 * // a shorthand object
2554 * useSearchParams({ tab: "1" });
2555 *
2556 * // object keys can be arrays for multiple values on the key
2557 * useSearchParams({ brand: ["nike", "reebok"] });
2558 *
2559 * // an array of tuples
2560 * useSearchParams([["tab", "1"]]);
2561 *
2562 * // a `URLSearchParams` object
2563 * useSearchParams(new URLSearchParams("?tab=1"));
2564 * ```
2565 * @returns A tuple of the current [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
2566 * and a function to update them.
2567 */
2568declare function useSearchParams(defaultInit?: URLSearchParamsInit): [URLSearchParams, SetURLSearchParams];
2569/**
2570 * Sets new search params and causes a navigation when called.
2571 *
2572 * ```tsx
2573 * <button
2574 * onClick={() => {
2575 * const params = new URLSearchParams();
2576 * params.set("someKey", "someValue");
2577 * setSearchParams(params, {
2578 * preventScrollReset: true,
2579 * });
2580 * }}
2581 * />
2582 * ```
2583 *
2584 * It also supports a function for setting new search params.
2585 *
2586 * ```tsx
2587 * <button
2588 * onClick={() => {
2589 * setSearchParams((prev) => {
2590 * prev.set("someKey", "someValue");
2591 * return prev;
2592 * });
2593 * }}
2594 * />
2595 * ```
2596 */
2597type SetURLSearchParams = (nextInit?: URLSearchParamsInit | ((prev: URLSearchParams) => URLSearchParamsInit), navigateOpts?: NavigateOptions) => void;
2598/**
2599 * Submits a HTML [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form)
2600 * to the server without reloading the page.
2601 */
2602interface SubmitFunction {
2603 (
2604 /**
2605 * Can be multiple types of elements and objects
2606 *
2607 * **[`HTMLFormElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement)**
2608 *
2609 * ```tsx
2610 * <Form
2611 * onSubmit={(event) => {
2612 * submit(event.currentTarget);
2613 * }}
2614 * />
2615 * ```
2616 *
2617 * **[`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)**
2618 *
2619 * ```tsx
2620 * const formData = new FormData();
2621 * formData.append("myKey", "myValue");
2622 * submit(formData, { method: "post" });
2623 * ```
2624 *
2625 * **Plain object that will be serialized as [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)**
2626 *
2627 * ```tsx
2628 * submit({ myKey: "myValue" }, { method: "post" });
2629 * ```
2630 *
2631 * **Plain object that will be serialized as JSON**
2632 *
2633 * ```tsx
2634 * submit(
2635 * { myKey: "myValue" },
2636 * { method: "post", encType: "application/json" }
2637 * );
2638 * ```
2639 */
2640 target: SubmitTarget,
2641 /**
2642 * Options that override the [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form)'s
2643 * own attributes. Required when submitting arbitrary data without a backing
2644 * [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form).
2645 */
2646 options?: SubmitOptions): Promise<void>;
2647}
2648/**
2649 * Submits a fetcher [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) to the server without reloading the page.
2650 */
2651interface FetcherSubmitFunction {
2652 (
2653 /**
2654 * Can be multiple types of elements and objects
2655 *
2656 * **[`HTMLFormElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement)**
2657 *
2658 * ```tsx
2659 * <fetcher.Form
2660 * onSubmit={(event) => {
2661 * fetcher.submit(event.currentTarget);
2662 * }}
2663 * />
2664 * ```
2665 *
2666 * **[`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)**
2667 *
2668 * ```tsx
2669 * const formData = new FormData();
2670 * formData.append("myKey", "myValue");
2671 * fetcher.submit(formData, { method: "post" });
2672 * ```
2673 *
2674 * **Plain object that will be serialized as [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)**
2675 *
2676 * ```tsx
2677 * fetcher.submit({ myKey: "myValue" }, { method: "post" });
2678 * ```
2679 *
2680 * **Plain object that will be serialized as JSON**
2681 *
2682 * ```tsx
2683 * fetcher.submit(
2684 * { myKey: "myValue" },
2685 * { method: "post", encType: "application/json" }
2686 * );
2687 * ```
2688 */
2689 target: SubmitTarget, options?: FetcherSubmitOptions): Promise<void>;
2690}
2691/**
2692 * The imperative version of {@link Form | `<Form>`} that lets you submit a form
2693 * from code instead of a user interaction.
2694 *
2695 * @example
2696 * import { useSubmit } from "react-router";
2697 *
2698 * function SomeComponent() {
2699 * const submit = useSubmit();
2700 * return (
2701 * <Form onChange={(event) => submit(event.currentTarget)} />
2702 * );
2703 * }
2704 *
2705 * @public
2706 * @category Hooks
2707 * @mode framework
2708 * @mode data
2709 * @returns A function that can be called to submit a {@link Form} imperatively.
2710 */
2711declare function useSubmit(): SubmitFunction;
2712/**
2713 * Resolves the URL to the closest route in the component hierarchy instead of
2714 * the current URL of the app.
2715 *
2716 * This is used internally by {@link Form} to resolve the `action` to the closest
2717 * route, but can be used generically as well.
2718 *
2719 * @example
2720 * import { useFormAction } from "react-router";
2721 *
2722 * function SomeComponent() {
2723 * // closest route URL
2724 * let action = useFormAction();
2725 *
2726 * // closest route URL + "destroy"
2727 * let destroyAction = useFormAction("destroy");
2728 * }
2729 *
2730 * @public
2731 * @category Hooks
2732 * @mode framework
2733 * @mode data
2734 * @param action The action to append to the closest route URL. Defaults to the
2735 * closest route URL.
2736 * @param options Options
2737 * @param options.relative The relative routing type to use when resolving the
2738 * action. Defaults to `"route"`.
2739 * @returns The resolved action URL.
2740 */
2741declare function useFormAction(action?: string, { relative }?: {
2742 relative?: RelativeRoutingType;
2743}): string;
2744/**
2745 * The return value {@link useFetcher} that keeps track of the state of a fetcher.
2746 *
2747 * ```tsx
2748 * let fetcher = useFetcher();
2749 * ```
2750 */
2751type FetcherWithComponents<TData> = Fetcher<TData> & {
2752 /**
2753 * Just like {@link Form} except it doesn't cause a navigation.
2754 *
2755 * ```tsx
2756 * function SomeComponent() {
2757 * const fetcher = useFetcher()
2758 * return (
2759 * <fetcher.Form method="post" action="/some/route">
2760 * <input type="text" />
2761 * </fetcher.Form>
2762 * )
2763 * }
2764 * ```
2765 */
2766 Form: React.ForwardRefExoticComponent<FetcherFormProps & React.RefAttributes<HTMLFormElement>>;
2767 /**
2768 * Submits form data to a route. While multiple nested routes can match a URL, only the leaf route will be called.
2769 *
2770 * The `formData` can be multiple types:
2771 *
2772 * - [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
2773 * A `FormData` instance.
2774 * - [`HTMLFormElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement)
2775 * A [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) DOM element.
2776 * - `Object`
2777 * An object of key/value-pairs that will be converted to a [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData)
2778 * instance by default. You can pass a more complex object and serialize it
2779 * as JSON by specifying `encType: "application/json"`. See
2780 * {@link useSubmit} for more details.
2781 *
2782 * If the method is `GET`, then the route [`loader`](../../start/framework/route-module#loader)
2783 * is being called and with the `formData` serialized to the url as [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams).
2784 * If `DELETE`, `PATCH`, `POST`, or `PUT`, then the route [`action`](../../start/framework/route-module#action)
2785 * is being called with `formData` as the body.
2786 *
2787 * ```tsx
2788 * // Submit a FormData instance (GET request)
2789 * const formData = new FormData();
2790 * fetcher.submit(formData);
2791 *
2792 * // Submit the HTML form element
2793 * fetcher.submit(event.currentTarget.form, {
2794 * method: "POST",
2795 * });
2796 *
2797 * // Submit key/value JSON as a FormData instance
2798 * fetcher.submit(
2799 * { serialized: "values" },
2800 * { method: "POST" }
2801 * );
2802 *
2803 * // Submit raw JSON
2804 * fetcher.submit(
2805 * {
2806 * deeply: {
2807 * nested: {
2808 * json: "values",
2809 * },
2810 * },
2811 * },
2812 * {
2813 * method: "POST",
2814 * encType: "application/json",
2815 * }
2816 * );
2817 * ```
2818 */
2819 submit: FetcherSubmitFunction;
2820 /**
2821 * Loads data from a route. Useful for loading data imperatively inside user
2822 * events outside a normal button or form, like a combobox or search input.
2823 *
2824 * ```tsx
2825 * let fetcher = useFetcher()
2826 *
2827 * <input onChange={e => {
2828 * fetcher.load(`/search?q=${e.target.value}`)
2829 * }} />
2830 * ```
2831 */
2832 load: (href: string, opts?: {
2833 /**
2834 * Wraps the initial state update for this `fetcher.load` in a
2835 * [`ReactDOM.flushSync`](https://react.dev/reference/react-dom/flushSync)
2836 * call instead of the default [`React.startTransition`](https://react.dev/reference/react/startTransition).
2837 * This allows you to perform synchronous DOM actions immediately after the
2838 * update is flushed to the DOM.
2839 */
2840 flushSync?: boolean;
2841 }) => Promise<void>;
2842};
2843/**
2844 * Useful for creating complex, dynamic user interfaces that require multiple,
2845 * concurrent data interactions without causing a navigation.
2846 *
2847 * Fetchers track their own, independent state and can be used to load data, submit
2848 * forms, and generally interact with [`action`](../../start/framework/route-module#action)
2849 * and [`loader`](../../start/framework/route-module#loader) functions.
2850 *
2851 * @example
2852 * import { useFetcher } from "react-router"
2853 *
2854 * function SomeComponent() {
2855 * let fetcher = useFetcher()
2856 *
2857 * // states are available on the fetcher
2858 * fetcher.state // "idle" | "loading" | "submitting"
2859 * fetcher.data // the data returned from the action or loader
2860 *
2861 * // render a form
2862 * <fetcher.Form method="post" />
2863 *
2864 * // load data
2865 * fetcher.load("/some/route")
2866 *
2867 * // submit data
2868 * fetcher.submit(someFormRef, { method: "post" })
2869 * fetcher.submit(someData, {
2870 * method: "post",
2871 * encType: "application/json"
2872 * })
2873 * }
2874 *
2875 * @public
2876 * @category Hooks
2877 * @mode framework
2878 * @mode data
2879 * @param options Options
2880 * @param options.key A unique key to identify the fetcher.
2881 *
2882 * By default, `useFetcher` generates a unique fetcher scoped to that component.
2883 * If you want to identify a fetcher with your own key such that you can access
2884 * it from elsewhere in your app, you can do that with the `key` option:
2885 *
2886 * ```tsx
2887 * function SomeComp() {
2888 * let fetcher = useFetcher({ key: "my-key" })
2889 * // ...
2890 * }
2891 *
2892 * // Somewhere else
2893 * function AnotherComp() {
2894 * // this will be the same fetcher, sharing the state across the app
2895 * let fetcher = useFetcher({ key: "my-key" });
2896 * // ...
2897 * }
2898 * ```
2899 * @returns A {@link FetcherWithComponents} object that contains the fetcher's state, data, and components for submitting forms and loading data.
2900 */
2901declare function useFetcher<T = any>({ key, }?: {
2902 key?: string;
2903}): FetcherWithComponents<SerializeFrom<T>>;
2904/**
2905 * Returns an array of all in-flight {@link Fetcher}s. This is useful for components
2906 * throughout the app that didn't create the fetchers but want to use their submissions
2907 * to participate in optimistic UI.
2908 *
2909 * @example
2910 * import { useFetchers } from "react-router";
2911 *
2912 * function SomeComponent() {
2913 * const fetchers = useFetchers();
2914 * fetchers[0].formData; // FormData
2915 * fetchers[0].state; // etc.
2916 * // ...
2917 * }
2918 *
2919 * @public
2920 * @category Hooks
2921 * @mode framework
2922 * @mode data
2923 * @returns An array of all in-flight {@link Fetcher}s, each with a unique `key`
2924 * property.
2925 */
2926declare function useFetchers(): (Fetcher & {
2927 key: string;
2928})[];
2929/**
2930 * When rendered inside a {@link RouterProvider}, will restore scroll positions
2931 * on navigations
2932 *
2933 * <!--
2934 * Not marked `@public` because we only export as UNSAFE_ and therefore we don't
2935 * maintain an .md file for this hook
2936 * -->
2937 *
2938 * @name UNSAFE_useScrollRestoration
2939 * @category Hooks
2940 * @mode framework
2941 * @mode data
2942 * @param options Options
2943 * @param options.getKey A function that returns a key to use for scroll restoration.
2944 * This is useful for custom scroll restoration logic, such as using only the pathname
2945 * so that subsequent navigations to prior paths will restore the scroll. Defaults
2946 * to `location.key`.
2947 * @param options.storageKey The key to use for storing scroll positions in
2948 * `sessionStorage`. Defaults to `"react-router-scroll-positions"`.
2949 * @returns {void}
2950 */
2951declare function useScrollRestoration({ getKey, storageKey, }?: {
2952 getKey?: GetScrollRestorationKeyFunction;
2953 storageKey?: string;
2954}): void;
2955/**
2956 * Set up a callback to be fired on [Window's `beforeunload` event](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event).
2957 *
2958 * @public
2959 * @category Hooks
2960 * @param callback The callback to be called when the [`beforeunload` event](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event)
2961 * is fired.
2962 * @param options Options
2963 * @param options.capture If `true`, the event will be captured during the capture
2964 * phase. Defaults to `false`.
2965 * @returns {void}
2966 */
2967declare function useBeforeUnload(callback: (event: BeforeUnloadEvent) => any, options?: {
2968 capture?: boolean;
2969}): void;
2970/**
2971 * Wrapper around {@link useBlocker} to show a [`window.confirm`](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm)
2972 * prompt to users instead of building a custom UI with {@link useBlocker}.
2973 *
2974 * The `unstable_` flag will not be removed because this technique has a lot of
2975 * rough edges and behaves very differently (and incorrectly sometimes) across
2976 * browsers if users click addition back/forward navigations while the
2977 * confirmation is open. Use at your own risk.
2978 *
2979 * @example
2980 * function ImportantForm() {
2981 * let [value, setValue] = React.useState("");
2982 *
2983 * // Block navigating elsewhere when data has been entered into the input
2984 * unstable_usePrompt({
2985 * message: "Are you sure?",
2986 * when: ({ currentLocation, nextLocation }) =>
2987 * value !== "" &&
2988 * currentLocation.pathname !== nextLocation.pathname,
2989 * });
2990 *
2991 * return (
2992 * <Form method="post">
2993 * <label>
2994 * Enter some important data:
2995 * <input
2996 * name="data"
2997 * value={value}
2998 * onChange={(e) => setValue(e.target.value)}
2999 * />
3000 * </label>
3001 * <button type="submit">Save</button>
3002 * </Form>
3003 * );
3004 * }
3005 *
3006 * @name unstable_usePrompt
3007 * @public
3008 * @category Hooks
3009 * @mode framework
3010 * @mode data
3011 * @param options Options
3012 * @param options.message The message to show in the confirmation dialog.
3013 * @param options.when A boolean or a function that returns a boolean indicating
3014 * whether to block the navigation. If a function is provided, it will receive an
3015 * object with `currentLocation` and `nextLocation` properties.
3016 * @returns {void}
3017 */
3018declare function usePrompt({ when, message, }: {
3019 when: boolean | BlockerFunction;
3020 message: string;
3021}): void;
3022/**
3023 * This hook returns `true` when there is an active [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API)
3024 * to the specified location. This can be used to apply finer-grained styles to
3025 * elements to further customize the view transition. This requires that view
3026 * transitions have been enabled for the given navigation via {@link LinkProps.viewTransition}
3027 * (or the `Form`, `submit`, or `navigate` call)
3028 *
3029 * @public
3030 * @category Hooks
3031 * @mode framework
3032 * @mode data
3033 * @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).
3034 * @param options Options
3035 * @param options.relative The relative routing type to use when resolving the
3036 * `to` location, defaults to `"route"`. See {@link RelativeRoutingType} for more details.
3037 * @returns `true` if there is an active [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API)
3038 * to the specified {@link Location}, otherwise `false`.
3039 */
3040declare function useViewTransitionState(to: To, { relative }?: {
3041 relative?: RelativeRoutingType;
3042}): boolean;
3043
3044interface StaticRouterProps {
3045 basename?: string;
3046 children?: React.ReactNode;
3047 location: Partial<Location> | string;
3048}
3049/**
3050 * A `<Router>` that may not navigate to any other location. This is useful
3051 * on the server where there is no stateful UI.
3052 *
3053 * @public
3054 * @category Declarative Routers
3055 * @mode declarative
3056 * @param props Props
3057 * @param props.basename The base URL for the static router (default: `/`)
3058 * @param props.children The child elements to render inside the static router
3059 * @param props.location The location to render the static router at (default: `/`)
3060 * @returns A React element that renders the static router
3061 */
3062declare function StaticRouter({ basename, children, location: locationProp, }: StaticRouterProps): React.JSX.Element;
3063interface StaticRouterProviderProps {
3064 context: StaticHandlerContext;
3065 router: Router$1;
3066 hydrate?: boolean;
3067 nonce?: string;
3068}
3069/**
3070 * A Data Router that may not navigate to any other location. This is useful
3071 * on the server where there is no stateful UI.
3072 *
3073 * @example
3074 * export async function handleRequest(request: Request) {
3075 * let { query, dataRoutes } = createStaticHandler(routes);
3076 * let context = await query(request));
3077 *
3078 * if (context instanceof Response) {
3079 * return context;
3080 * }
3081 *
3082 * let router = createStaticRouter(dataRoutes, context);
3083 * return new Response(
3084 * ReactDOMServer.renderToString(<StaticRouterProvider ... />),
3085 * { headers: { "Content-Type": "text/html" } }
3086 * );
3087 * }
3088 *
3089 * @public
3090 * @category Data Routers
3091 * @mode data
3092 * @param props Props
3093 * @param props.context The {@link StaticHandlerContext} returned from `staticHandler.query()`
3094 * @param props.router The static data router from {@link createStaticRouter}
3095 * @param props.hydrate Whether to hydrate the router on the client (default `true`)
3096 * @param props.nonce The [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/nonce)
3097 * to use for the hydration `<script>` tag
3098 * @returns A React element that renders the static router provider
3099 */
3100declare function StaticRouterProvider({ context, router, hydrate, nonce, }: StaticRouterProviderProps): React.JSX.Element;
3101type CreateStaticHandlerOptions = Omit<CreateStaticHandlerOptions$1, "mapRouteProperties">;
3102/**
3103 * Create a static handler to perform server-side data loading
3104 *
3105 * @example
3106 * export async function handleRequest(request: Request) {
3107 * let { query, dataRoutes } = createStaticHandler(routes);
3108 * let context = await query(request));
3109 *
3110 * if (context instanceof Response) {
3111 * return context;
3112 * }
3113 *
3114 * let router = createStaticRouter(dataRoutes, context);
3115 * return new Response(
3116 * ReactDOMServer.renderToString(<StaticRouterProvider ... />),
3117 * { headers: { "Content-Type": "text/html" } }
3118 * );
3119 * }
3120 *
3121 * @public
3122 * @category Data Routers
3123 * @mode data
3124 * @param routes The route objects to create a static handler for
3125 * @param opts Options
3126 * @param opts.basename The base URL for the static handler (default: `/`)
3127 * @param opts.future Future flags for the static handler
3128 * @returns A static handler that can be used to query data for the provided routes
3129 */
3130declare function createStaticHandler(routes: RouteObject[], opts?: CreateStaticHandlerOptions): StaticHandler;
3131/**
3132 * Create a static data router for server-side rendering
3133 *
3134 * @example
3135 * export async function handleRequest(request: Request) {
3136 * let { query, dataRoutes } = createStaticHandler(routes);
3137 * let context = await query(request));
3138 *
3139 * if (context instanceof Response) {
3140 * return context;
3141 * }
3142 *
3143 * let router = createStaticRouter(dataRoutes, context);
3144 * return new Response(
3145 * ReactDOMServer.renderToString(<StaticRouterProvider ... />),
3146 * { headers: { "Content-Type": "text/html" } }
3147 * );
3148 * }
3149 *
3150 * @public
3151 * @category Data Routers
3152 * @mode data
3153 * @param routes The route objects to create a static data router for
3154 * @param context The static handler context returned from `staticHandler.query()`
3155 * @param opts Options
3156 * @param opts.future Future flags for the static data router
3157 * @returns A static data router that can be used to render the provided routes
3158 */
3159declare function createStaticRouter(routes: RouteObject[], context: StaticHandlerContext, opts?: {
3160 future?: Partial<FutureConfig$1>;
3161}): Router$1;
3162
3163export { ScrollRestoration as $, type AssetsManifest as A, type BrowserRouterProps as B, type ScrollRestorationProps as C, type DOMRouterOpts as D, type EntryContext as E, type FutureConfig as F, type SetURLSearchParams as G, type HydrateFallbackType as H, type IndexRouteProps as I, type SubmitFunction as J, type FetcherSubmitFunction as K, type LayoutRouteProps as L, type MemoryRouterOpts as M, type NavigateProps as N, type OutletProps as O, type PathRouteProps as P, type FetcherWithComponents as Q, type RouteComponentType as R, type ServerBuild as S, createBrowserRouter as T, createHashRouter as U, BrowserRouter as V, HashRouter as W, Link as X, HistoryRouter as Y, NavLink as Z, Form as _, type ErrorBoundaryType as a, useLinkClickHandler as a0, useSearchParams as a1, useSubmit as a2, useFormAction as a3, useFetcher as a4, useFetchers as a5, useBeforeUnload as a6, usePrompt as a7, useViewTransitionState as a8, type FetcherSubmitOptions as a9, WithHydrateFallbackProps as aA, withHydrateFallbackProps as aB, WithErrorBoundaryProps as aC, withErrorBoundaryProps as aD, FrameworkContext as aE, createClientRoutes as aF, createClientRoutesWithHMRRevalidationOptOut as aG, shouldHydrateRouteLoader as aH, useScrollRestoration as aI, type ParamKeyValuePair as aa, type SubmitOptions as ab, type URLSearchParamsInit as ac, type SubmitTarget as ad, createSearchParams as ae, type StaticRouterProps as af, type StaticRouterProviderProps as ag, createStaticHandler as ah, createStaticRouter as ai, StaticRouter as aj, StaticRouterProvider as ak, Meta as al, Links as am, Scripts as an, PrefetchPageLinks as ao, type ScriptsProps as ap, type PrefetchBehavior as aq, type DiscoverBehavior as ar, type HandleDataRequestFunction as as, type HandleDocumentRequestFunction as at, type HandleErrorFunction as au, type ServerEntryModule as av, hydrationRouteProperties as aw, mapRouteProperties as ax, WithComponentProps as ay, withComponentProps as az, type AwaitProps as b, type MemoryRouterProps as c, type RouteProps as d, type RouterProps as e, type RouterProviderProps as f, type RoutesProps as g, Await as h, MemoryRouter as i, Navigate as j, Outlet as k, Route$1 as l, Router as m, RouterProvider as n, Routes as o, createMemoryRouter as p, createRoutesFromChildren as q, createRoutesFromElements as r, renderMatches as s, type HashRouterProps as t, type HistoryRouterProps as u, type LinkProps as v, type NavLinkProps as w, type NavLinkRenderProps as x, type FetcherFormProps as y, type FormProps as z };
3164
\No newline at end of file