index-react-server-client-CCjKYJTH.d.ts 90 KB

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