react-router
- Version 7.0.2
- Published
- 2.27 MB
- 4 dependencies
- MIT license
Install
npm i react-router
yarn add react-router
pnpm add react-router
Overview
Declarative routing for React
Index
Variables
- createRequestHandler
- createRoutesFromElements
- createSession
- Form
- IDLE_BLOCKER
- IDLE_FETCHER
- IDLE_NAVIGATION
- isCookie
- isSession
- Link
- NavLink
- redirect
- redirectDocument
- replace
- UNSAFE_DataRouterContext
- UNSAFE_DataRouterStateContext
- UNSAFE_FetchersContext
- UNSAFE_FrameworkContext
- UNSAFE_LocationContext
- UNSAFE_NavigationContext
- UNSAFE_RouteContext
- UNSAFE_SingleFetchRedirectSymbol
- UNSAFE_ViewTransitionContext
Functions
- Await()
- BrowserRouter()
- createBrowserRouter()
- createCookie()
- createCookieSessionStorage()
- createHashRouter()
- createMemoryRouter()
- createMemorySessionStorage()
- createPath()
- createRoutesFromChildren()
- createRoutesStub()
- createSearchParams()
- createSessionStorage()
- createStaticHandler()
- createStaticRouter()
- data()
- generatePath()
- HashRouter()
- isRouteErrorResponse()
- Links()
- matchPath()
- matchRoutes()
- MemoryRouter()
- Meta()
- Navigate()
- Outlet()
- parsePath()
- PrefetchPageLinks()
- renderMatches()
- resolvePath()
- Route()
- Router()
- RouterProvider()
- Routes()
- Scripts()
- ScrollRestoration()
- ServerRouter()
- StaticRouter()
- StaticRouterProvider()
- UNSAFE_createBrowserHistory()
- UNSAFE_createClientRoutes()
- UNSAFE_createClientRoutesWithHMRRevalidationOptOut()
- UNSAFE_createRouter()
- UNSAFE_decodeViaTurboStream()
- UNSAFE_deserializeErrors()
- UNSAFE_getPatchRoutesOnNavigationFunction()
- UNSAFE_getSingleFetchDataStrategy()
- UNSAFE_invariant()
- UNSAFE_mapRouteProperties()
- UNSAFE_shouldHydrateRouteLoader()
- UNSAFE_useFogOFWarDiscovery()
- UNSAFE_useScrollRestoration()
- unstable_HistoryRouter()
- unstable_setDevServerHooks()
- unstable_usePrompt()
- useActionData()
- useAsyncError()
- useAsyncValue()
- useBeforeUnload()
- useBlocker()
- useFetcher()
- useFetchers()
- useFormAction()
- useHref()
- useInRouterContext()
- useLinkClickHandler()
- useLoaderData()
- useLocation()
- useMatch()
- useMatches()
- useNavigate()
- useNavigation()
- useNavigationType()
- useOutlet()
- useOutletContext()
- useParams()
- useResolvedPath()
- useRevalidator()
- useRouteError()
- useRouteLoaderData()
- useRoutes()
- useSearchParams()
- useSubmit()
- useViewTransitionState()
Classes
Interfaces
Enums
Type Aliases
- Blocker
- BlockerFunction
- ClientActionFunction
- ClientActionFunctionArgs
- ClientLoaderFunction
- ClientLoaderFunctionArgs
- CookieOptions
- CreateRequestHandlerFunction
- DataRouteObject
- ErrorResponse
- Fetcher
- FetcherWithComponents
- FlashSessionData
- FormEncType
- FormMethod
- HeadersArgs
- HTMLFormMethod
- HtmlLinkDescriptor
- HydrationState
- InitialEntry
- IsCookieFunction
- IsSessionFunction
- LinkDescriptor
- LoaderFunction
- MetaDescriptor
- Navigation
- NavigationStates
- NavLinkRenderProps
- ParamKeyValuePair
- ParamParseKey
- Params
- PatchRoutesOnNavigationFunction
- PatchRoutesOnNavigationFunctionArgs
- PathParam
- RedirectFunction
- RelativeRoutingType
- RequestHandler
- RevalidationState
- RouteObject
- RouteProps
- RouterFetchOptions
- RouterNavigateOptions
- ScriptsProps
- ScrollRestorationProps
- SetURLSearchParams
- SubmitTarget
- To
- URLSearchParamsInit
Namespaces
Variables
variable createRequestHandler
const createRequestHandler: CreateRequestHandlerFunction;
variable createRoutesFromElements
let createRoutesFromElements: ( children: React.ReactNode, parentPath?: number[]) => RouteObject[];
Create route objects from JSX elements instead of arrays of objects
variable createSession
const createSession: CreateSessionFunction;
Creates a new Session object.
Note: This function is typically not invoked directly by application code. Instead, use a
SessionStorage
object'sgetSession
method.See Also
https://remix.run/utils/sessions#createsession
variable Form
const Form: React.ForwardRefExoticComponent<any>;
A progressively enhanced HTML [
<form>
](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) that submits data to actions viafetch
, activating pending states inuseNavigation
which enables advanced user interfaces beyond a basic HTML form. After a form's action completes, all data on the page is automatically revalidated to keep the UI in sync with the data.Because it uses the HTML form API, server rendered pages are interactive at a basic level before JavaScript loads. Instead of React Router managing the submission, the browser manages the submission as well as the pending states (like the spinning favicon). After JavaScript loads, React Router takes over enabling web application user experiences.
Form is most useful for submissions that should also change the URL or otherwise add an entry to the browser history stack. For forms that shouldn't manipulate the browser history stack, use [
<fetcher.Form>
][fetcher_form].import { Form } from "react-router";function NewEvent() {return (<Form action="/events" method="post"><input name="title" type="text" /><input name="description" type="text" /></Form>)}Components
variable IDLE_BLOCKER
const IDLE_BLOCKER: BlockerUnblocked;
variable IDLE_FETCHER
const IDLE_FETCHER: { state: 'idle'; formMethod: undefined; formAction: undefined; formEncType: undefined; text: undefined; formData: undefined; json: undefined; data: any;};
variable IDLE_NAVIGATION
const IDLE_NAVIGATION: { state: 'idle'; location: undefined; formMethod: undefined; formAction: undefined; formEncType: undefined; formData: undefined; json: undefined; text: undefined;};
variable isCookie
const isCookie: IsCookieFunction;
Returns true if an object is a Remix cookie container.
See Also
https://remix.run/utils/cookies#iscookie
variable isSession
const isSession: IsSessionFunction;
Returns true if an object is a Remix session.
See Also
https://remix.run/utils/sessions#issession
variable Link
const Link: React.ForwardRefExoticComponent<any>;
A progressively enhanced
<a href>
wrapper to enable navigation with client-side routing.```tsx import { Link } from "react-router";
Dashboard;
<Link to={{ pathname: "/some/path", search: "?query=string", hash: "#hash", }} /> ```
Components
variable NavLink
const NavLink: React.ForwardRefExoticComponent<any>;
Wraps `<Link>` with additional props for styling active and pending states.
- Automatically applies classes to the link based on its active and pending states, see NavLinkProps.className. - Automatically applies
aria-current="page"
to the link when the link is active. See [aria-current
](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-current) on MDN.```tsx import { NavLink } from "react-router" ```
States are available through the className, style, and children render props. See NavLinkRenderProps.
```tsx <NavLink to="/messages" className={({ isActive, isPending }) => isPending ? "pending" : isActive ? "active" : "" } > Messages ```
Components
variable redirect
const redirect: RedirectFunction;
A redirect response. Sets the status code and the
Location
header. Defaults to "302 Found".Utils
variable redirectDocument
const redirectDocument: RedirectFunction;
A redirect response that will force a document reload to the new location. Sets the status code and the
Location
header. Defaults to "302 Found".Utils
variable replace
const replace: RedirectFunction;
A redirect response that will perform a
history.replaceState
instead of ahistory.pushState
for client-side navigation redirects. Sets the status code and theLocation
header. Defaults to "302 Found".Utils
variable UNSAFE_DataRouterContext
const UNSAFE_DataRouterContext: React.Context<DataRouterContextObject>;
variable UNSAFE_DataRouterStateContext
const UNSAFE_DataRouterStateContext: React.Context<RouterState>;
variable UNSAFE_FetchersContext
const UNSAFE_FetchersContext: React.Context<FetchersContextObject>;
variable UNSAFE_FrameworkContext
const UNSAFE_FrameworkContext: React.Context<FrameworkContextObject>;
variable UNSAFE_LocationContext
const UNSAFE_LocationContext: React.Context<LocationContextObject>;
variable UNSAFE_NavigationContext
const UNSAFE_NavigationContext: React.Context<NavigationContextObject>;
variable UNSAFE_RouteContext
const UNSAFE_RouteContext: React.Context<RouteContextObject>;
variable UNSAFE_SingleFetchRedirectSymbol
const UNSAFE_SingleFetchRedirectSymbol: Symbol;
variable UNSAFE_ViewTransitionContext
const UNSAFE_ViewTransitionContext: React.Context<ViewTransitionContextObject>;
Functions
function Await
Await: <Resolve>({ children, errorElement, resolve,}: AwaitProps<Resolve>) => React.JSX.Element;
Used to render promise values with automatic error handling.
import { Await, useLoaderData } from "react-router";export function loader() {// not awaitedconst reviews = getReviews()// awaited (blocks the transition)const book = await fetch("/api/book").then((res) => res.json())return { book, reviews }}function Book() {const { book, reviews } = useLoaderData();return (<div><h1>{book.title}</h1><p>{book.description}</p><React.Suspense fallback={<ReviewsSkeleton />}><Awaitresolve={reviews}errorElement={<div>Could not load reviews 😬</div>}children={(resolvedReviews) => (<Reviews items={resolvedReviews} />)}/></React.Suspense></div>);}*Note:**
<Await>
expects to be rendered inside of a<React.Suspense>
Components
function BrowserRouter
BrowserRouter: ({ basename, children, window,}: BrowserRouterProps) => React.JSX.Element;
A
<Router>
for use in web browsers. Provides the cleanest URLs.Router Components
function createBrowserRouter
createBrowserRouter: (routes: RouteObject[], opts?: DOMRouterOpts) => Router$1;
Routers
function createCookie
createCookie: (name: string, cookieOptions?: CookieOptions) => Cookie;
Creates a logical container for managing a browser cookie from the server.
function createCookieSessionStorage
createCookieSessionStorage: <Data = SessionData, FlashData = Data>({ cookie: cookieArg,}?: CookieSessionStorageOptions) => SessionStorage<Data, FlashData>;
Creates and returns a SessionStorage object that stores all session data directly in the session cookie itself.
This has the advantage that no database or other backend services are needed, and can help to simplify some load-balanced scenarios. However, it also has the limitation that serialized session data may not exceed the browser's maximum cookie size. Trade-offs!
function createHashRouter
createHashRouter: (routes: RouteObject[], opts?: DOMRouterOpts) => Router$1;
Routers
function createMemoryRouter
createMemoryRouter: ( routes: RouteObject[], opts?: { basename?: string; future?: Partial<FutureConfig$1>; hydrationData?: HydrationState; initialEntries?: InitialEntry[]; initialIndex?: number; dataStrategy?: DataStrategyFunction; patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction; }) => Router$1;
Routers
function createMemorySessionStorage
createMemorySessionStorage: <Data = SessionData, FlashData = Data>({ cookie,}?: MemorySessionStorageOptions) => SessionStorage<Data, FlashData>;
Creates and returns a simple in-memory SessionStorage object, mostly useful for testing and as a reference implementation.
Note: This storage does not scale beyond a single process, so it is not suitable for most production scenarios.
function createPath
createPath: ({ pathname, search, hash }: Partial<Path>) => string;
Creates a string URL path from the given pathname, search, and hash components.
Utils
function createRoutesFromChildren
createRoutesFromChildren: ( children: React.ReactNode, parentPath?: number[]) => RouteObject[];
Creates a route config from a React "children" object, which is usually either a
<Route>
element or an array of them. Used internally by<Routes>
to create a route config from its children.Utils
function createRoutesStub
createRoutesStub: ( routes: StubRouteObject[], context?: AppLoadContext) => ({ initialEntries, initialIndex, hydrationData, future,}: RoutesTestStubProps) => React.JSX.Element;
Utils
function createSearchParams
createSearchParams: (init?: URLSearchParamsInit) => URLSearchParams;
Creates a URLSearchParams object using the given initializer.
This is identical to
new URLSearchParams(init)
except it also supports arrays as values in the object form of the initializer instead of just strings. This is convenient when you need multiple values for a given key, but don't want to use an array initializer.For example, instead of:
```tsx let searchParams = new URLSearchParams([ ['sort', 'name'], ['sort', 'price'] ]); ``` you can do:
``` let searchParams = createSearchParams({ sort: ['name', 'price'] }); ```
Utils
function createSessionStorage
createSessionStorage: <Data = SessionData, FlashData = Data>({ cookie: cookieArg, createData, readData, updateData, deleteData,}: SessionIdStorageStrategy<Data, FlashData>) => SessionStorage<Data, FlashData>;
Creates a SessionStorage object using a SessionIdStorageStrategy.
Note: This is a low-level API that should only be used if none of the existing session storage options meet your requirements.
function createStaticHandler
createStaticHandler: ( routes: RouteObject[], opts?: CreateStaticHandlerOptions) => StaticHandler;
Utils
function createStaticRouter
createStaticRouter: ( routes: RouteObject[], context: StaticHandlerContext, opts?: { future?: Partial<FutureConfig$1> }) => Router;
Routers
function data
data: <D>(data: D, init?: number | ResponseInit) => DataWithResponseInit<D>;
Create "responses" that contain
status
/headers
without forcing serialization into an actualResponse
- used by Remix single fetchUtils
function generatePath
generatePath: <Path extends string>( originalPath: Path, params?: { [key in PathParam<Path>]: string }) => string;
Returns a path with params interpolated.
Utils
function HashRouter
HashRouter: ({ basename, children, window,}: HashRouterProps) => React.JSX.Element;
A
<Router>
for use in web browsers. Stores the location in the hash portion of the URL so it is not sent to the server.Router Components
function isRouteErrorResponse
isRouteErrorResponse: (error: any) => error is ErrorResponse;
Check if the given error is an ErrorResponse generated from a 4xx/5xx Response thrown from an action/loader
Utils
function Links
Links: () => React.JSX.Element;
Renders all of the
<link>
tags created by route module LinksFunction export. You should render it inside the<head>
of your document.```tsx import { Links } from "react-router";
export default function Root() { return ( ); } ```
Components
function matchPath
matchPath: <ParamKey extends ParamParseKey<Path>, Path extends string>( pattern: PathPattern<Path> | Path, pathname: string) => PathMatch<ParamKey> | null;
Performs pattern matching on a URL pathname and returns information about the match.
Utils
function matchRoutes
matchRoutes: <RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject>( routes: RouteObjectType[], locationArg: Partial<Location> | string, basename?: string) => AgnosticRouteMatch<string, RouteObjectType>[] | null;
Matches the given routes to a location and returns the match data.
Utils
function MemoryRouter
MemoryRouter: ({ basename, children, initialEntries, initialIndex,}: MemoryRouterProps) => React.ReactElement;
A
<Router>
that stores all entries in memory.Router Components
function Meta
Meta: () => React.JSX.Element;
Renders all the
<meta>
tags created by route module MetaFunction exports. You should render it inside the<head>
of your HTML.```tsx import { Meta } from "react-router";
export default function Root() { return ( ); } ```
Components
function Navigate
Navigate: ({ to, replace, state, relative }: NavigateProps) => null;
A component-based version of useNavigate to use in a [`React.Component Class`](https://reactjs.org/docs/react-component.html) where hooks are not able to be used.
It's recommended to avoid using this component in favor of useNavigate
Components
function Outlet
Outlet: (props: OutletProps) => React.ReactElement | null;
Renders the matching child route of a parent route or nothing if no child route matches.
```tsx import { Outlet } from "react-router"
export default function SomeParent() { return ( Parent Content ); } ```
Components
function parsePath
parsePath: (path: string) => Partial<Path>;
Parses a string URL path into its separate pathname, search, and hash components.
Utils
function PrefetchPageLinks
PrefetchPageLinks: ({ page, ...dataLinkProps}: PageLinkDescriptor) => React.JSX.Element | null;
Renders
<link rel=prefetch|modulepreload>
tags for modules and data of another page to enable an instant navigation to that page. `<Link prefetch>` uses this internally, but you can render it to prefetch a page for any other reason.```tsx import { PrefetchPageLinks } from "react-router"
```
For example, you may render one of this as the user types into a search field to prefetch search results before they click through to their selection.
Components
function renderMatches
renderMatches: (matches: RouteMatch[] | null) => React.ReactElement | null;
Renders the result of
matchRoutes()
into a React element.Utils
function resolvePath
resolvePath: (to: To, fromPathname?: string) => Path;
Returns a resolved path object relative to the given pathname.
Utils
function Route
Route: (_props: RouteProps) => React.ReactElement | null;
Configures an element to render when a pattern matches the current location. It must be rendered within a Routes element. Note that these routes do not participate in data loading, actions, code splitting, or any other route module features.
Components
function Router
Router: ({ basename: basenameProp, children, location: locationProp, navigationType, navigator, static: staticProp,}: RouterProps) => React.ReactElement | null;
Provides location context for the rest of the app.
Note: You usually won't render a
<Router>
directly. Instead, you'll render a router that is more specific to your environment such as a<BrowserRouter>
in web browsers or a<StaticRouter>
for server rendering.Components
function RouterProvider
RouterProvider: ({ router, flushSync: reactDomFlushSyncImpl,}: RouterProviderProps) => React.ReactElement;
Given a Remix Router instance, render the appropriate UI
function Routes
Routes: ({ children, location }: RoutesProps) => React.ReactElement | null;
Renders a branch of `<Routes>` that best matches the current location. Note that these routes do not participate in data loading, actions, code splitting, or any other route module features.
```tsx import { Routes, Route } from "react-router"
<Route index element={} /> <Route path="step-2" element={} /> <Route path="step-3" element={}> ```
Components
function Scripts
Scripts: (props: ScriptsProps) => React.JSX.Element | null;
Renders the client runtime of your app. It should be rendered inside the
<body>
of the document.```tsx import { Scripts } from "react-router";
export default function Root() { return ( ); } ```
If server rendering, you can omit
<Scripts/>
and the app will work as a traditional web app without JavaScript, relying solely on HTML and browser behaviors.Components
function ScrollRestoration
ScrollRestoration: typeof ScrollRestoration;
Emulates the browser's scroll restoration on location changes. Apps should only render one of these, right before the Scripts component.
```tsx import { ScrollRestoration } from "react-router";
export default function Root() { return ( ); } ```
This component renders an inline
<script>
to prevent scroll flashing. Thenonce
prop will be passed down to the script tag to allow CSP nonce usage.```tsx <ScrollRestoration nonce={cspNonce} /> ```
Components
function ServerRouter
ServerRouter: ({ context, url, abortDelay, nonce,}: ServerRouterProps) => ReactElement;
The entry point for a Remix app when it is rendered on the server (in
app/entry.server.js
). This component is used to generate the HTML in the response from the server.Components
function StaticRouter
StaticRouter: ({ basename, children, location: locationProp,}: StaticRouterProps) => React.JSX.Element;
A
<Router>
that may not navigate to any other location. This is useful on the server where there is no stateful UI.Router Components
function StaticRouterProvider
StaticRouterProvider: ({ context, router, hydrate, nonce,}: StaticRouterProviderProps) => React.JSX.Element;
A Data Router that may not navigate to any other location. This is useful on the server where there is no stateful UI.
Router Components
function UNSAFE_createBrowserHistory
UNSAFE_createBrowserHistory: (options?: BrowserHistoryOptions) => BrowserHistory;
Browser history stores the location in regular URLs. This is the standard for most web apps, but it requires some configuration on the server to ensure you serve the same app at multiple URLs.
See Also
https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
function UNSAFE_createClientRoutes
UNSAFE_createClientRoutes: ( manifest: RouteManifest<EntryRoute>, routeModulesCache: RouteModules, initialState: HydrationState | null, isSpaMode: boolean, parentId?: string, routesByParentId?: Record<string, Omit<EntryRoute, 'children'>[]>, needsRevalidation?: Set<string>) => DataRouteObject[];
function UNSAFE_createClientRoutesWithHMRRevalidationOptOut
UNSAFE_createClientRoutesWithHMRRevalidationOptOut: ( needsRevalidation: Set<string>, manifest: RouteManifest<EntryRoute>, routeModulesCache: RouteModules, initialState: HydrationState, future: FutureConfig, isSpaMode: boolean) => DataRouteObject[];
function UNSAFE_createRouter
UNSAFE_createRouter: (init: RouterInit) => Router;
Create a router and listen to history POP navigations
function UNSAFE_decodeViaTurboStream
UNSAFE_decodeViaTurboStream: ( body: ReadableStream<Uint8Array>, global: Window | typeof globalThis) => Promise<{ done: Promise<undefined>; value: unknown }>;
function UNSAFE_deserializeErrors
UNSAFE_deserializeErrors: ( errors: RouterState['errors']) => RouterState['errors'];
function UNSAFE_getPatchRoutesOnNavigationFunction
UNSAFE_getPatchRoutesOnNavigationFunction: ( manifest: AssetsManifest, routeModules: RouteModules, isSpaMode: boolean, basename: string | undefined) => PatchRoutesOnNavigationFunction | undefined;
function UNSAFE_getSingleFetchDataStrategy
UNSAFE_getSingleFetchDataStrategy: ( manifest: AssetsManifest, routeModules: RouteModules, getRouter: () => Router) => DataStrategyFunction;
function UNSAFE_invariant
UNSAFE_invariant: { (value: boolean, message?: string): asserts value; <T>(value: T, message?: string): asserts value is T;};
function UNSAFE_mapRouteProperties
UNSAFE_mapRouteProperties: ( route: RouteObject) => Partial<RouteObject> & { hasErrorBoundary: boolean };
function UNSAFE_shouldHydrateRouteLoader
UNSAFE_shouldHydrateRouteLoader: ( route: EntryRoute, routeModule: RouteModule, isSpaMode: boolean) => boolean;
function UNSAFE_useFogOFWarDiscovery
UNSAFE_useFogOFWarDiscovery: ( router: Router$1, manifest: AssetsManifest, routeModules: RouteModules, isSpaMode: boolean) => void;
function UNSAFE_useScrollRestoration
UNSAFE_useScrollRestoration: ({ getKey, storageKey,}?: { getKey?: GetScrollRestorationKeyFunction; storageKey?: string;}) => void;
When rendered inside a RouterProvider, will restore scroll positions on navigations
function unstable_HistoryRouter
unstable_HistoryRouter: typeof HistoryRouter;
A
<Router>
that accepts a pre-instantiated history object. It's important to note that using your own history object is highly discouraged and may add two versions of the history library to your bundles unless you use the same version of the history library that React Router uses internally.unstable_HistoryRouter Router Components
function unstable_setDevServerHooks
unstable_setDevServerHooks: (devServerHooks: DevServerHooks) => void;
function unstable_usePrompt
unstable_usePrompt: ({ when, message,}: { when: boolean | BlockerFunction; message: string;}) => void;
Wrapper around useBlocker to show a window.confirm prompt to users instead of building a custom UI with useBlocker.
The
unstable_
flag will not be removed because this technique has a lot of rough edges and behaves very differently (and incorrectly sometimes) across browsers if users click addition back/forward navigations while the confirmation is open. Use at your own risk.```tsx function ImportantForm() { let [value, setValue] = React.useState("");
// Block navigating elsewhere when data has been entered into the input unstable_usePrompt({ message: "Are you sure?", when: ({ currentLocation, nextLocation }) => value !== "" && currentLocation.pathname !== nextLocation.pathname, });
return ( Enter some important data: <input name="data" value={value} onChange={(e) => setValue(e.target.value)} /> Save ); } ```
Hooks unstable_usePrompt
function useActionData
useActionData: <T = any>() => SerializeFrom<T> | undefined;
Returns the action data from the most recent POST navigation form submission or
undefined
if there hasn't been one.```tsx import { Form, useActionData } from "react-router"
export async function action({ request }) { const body = await request.formData() const name = body.get("visitorsName") return { message:
Hello, ${name}
} }export default function Invoices() { const data = useActionData() return ( {data ? data.message : "Waiting..."} ) } ```
Hooks
function useAsyncError
useAsyncError: () => unknown;
Returns the rejection value from the closest `<Await>`.
```tsx import { Await, useAsyncError } from "react-router"
function ErrorElement() { const error = useAsyncError(); return ( Uh Oh, something went wrong! {error.message} ); }
// somewhere in your app <Await resolve={promiseThatRejects} errorElement={} /> ```
Hooks
function useAsyncValue
useAsyncValue: () => unknown;
Returns the resolved promise value from the closest `<Await>`.
```tsx function SomeDescendant() { const value = useAsyncValue(); // ... }
// somewhere in your app <Await resolve={somePromise}> ```
Hooks
function useBeforeUnload
useBeforeUnload: ( callback: (event: BeforeUnloadEvent) => any, options?: { capture?: boolean }) => void;
Setup a callback to be fired on the window's
beforeunload
event.Hooks
function useBlocker
useBlocker: (shouldBlock: boolean | BlockerFunction) => Blocker;
Allow the application to block navigations within the SPA and present the user a confirmation dialog to confirm the navigation. Mostly used to avoid using half-filled form data. This does not handle hard-reloads or cross-origin navigations.
Hooks
function useFetcher
useFetcher: <T = any>({ key,}?: { key?: string;}) => FetcherWithComponents<SerializeFrom<T>>;
Useful for creating complex, dynamic user interfaces that require multiple, concurrent data interactions without causing a navigation.
Fetchers track their own, independent state and can be used to load data, submit forms, and generally interact with loaders and actions.
```tsx import { useFetcher } from "react-router"
function SomeComponent() { let fetcher = useFetcher()
// states are available on the fetcher fetcher.state // "idle" | "loading" | "submitting" fetcher.data // the data returned from the action or loader
// render a form <fetcher.Form method="post" />
// load data fetcher.load("/some/route")
// submit data fetcher.submit(someFormRef, { method: "post" }) fetcher.submit(someData, { method: "post", encType: "application/json" }) } ```
Hooks
function useFetchers
useFetchers: () => (Fetcher & { key: string })[];
Returns an array of all in-flight fetchers. This is useful for components throughout the app that didn't create the fetchers but want to use their submissions to participate in optimistic UI.
```tsx import { useFetchers } from "react-router";
function SomeComponent() { const fetchers = useFetchers(); fetchers[0].formData; // FormData fetchers[0].state; // etc. // ... } ```
Hooks
function useFormAction
useFormAction: ( action?: string, { relative }?: { relative?: RelativeRoutingType }) => string;
Resolves the URL to the closest route in the component hierarchy instead of the current URL of the app.
This is used internally by Form resolve the action to the closest route, but can be used generically as well.
```tsx import { useFormAction } from "react-router";
function SomeComponent() { // closest route URL let action = useFormAction();
// closest route URL + "destroy" let destroyAction = useFormAction("destroy"); } ```
Hooks
function useHref
useHref: (to: To, { relative }?: { relative?: RelativeRoutingType }) => string;
Resolves a URL against the current location.
```tsx import { useHref } from "react-router"
function SomeComponent() { let href = useHref("some/where"); // "/resolved/some/where" } ```
Hooks
function useInRouterContext
useInRouterContext: () => boolean;
Returns true if this component is a descendant of a Router, useful to ensure a component is used within a Router.
Hooks
function useLinkClickHandler
useLinkClickHandler: <E extends Element = HTMLAnchorElement>( to: To, { target, replace: replaceProp, state, preventScrollReset, relative, viewTransition, }?: { target?: React.HTMLAttributeAnchorTarget; replace?: boolean; state?: any; preventScrollReset?: boolean; relative?: RelativeRoutingType; viewTransition?: boolean; }) => (event: React.MouseEvent<E, MouseEvent>) => void;
Handles the click behavior for router
<Link>
components. This is useful if you need to create custom<Link>
components with the same click behavior we use in our exported<Link>
.Hooks
function useLoaderData
useLoaderData: <T = any>() => SerializeFrom<T>;
Returns the data from the closest route loader or client loader.
```tsx import { useLoaderData } from "react-router"
export async function loader() { return await fakeDb.invoices.findAll(); }
export default function Invoices() { let invoices = useLoaderData<typeof loader>(); // ... } ```
Hooks
function useLocation
useLocation: () => Location;
Returns the current Location. This can be useful if you'd like to perform some side effect whenever it changes.
```tsx import * as React from 'react' import { useLocation } from 'react-router'
function SomeComponent() { let location = useLocation()
React.useEffect(() => { // Google Analytics ga('send', 'pageview') }, [location]);
return ( // ... ); } ```
Hooks
function useMatch
useMatch: <ParamKey extends ParamParseKey<Path>, Path extends string>( pattern: PathPattern<Path> | Path) => PathMatch<ParamKey> | null;
Returns a PathMatch object if the given pattern matches the current URL. This is useful for components that need to know "active" state, e.g.
<NavLink>
.Hooks
function useMatches
useMatches: () => UIMatch[];
Returns the active route matches, useful for accessing loaderData for parent/child routes or the route "handle" property
Hooks
function useNavigate
useNavigate: () => NavigateFunction;
Returns a function that lets you navigate programmatically in the browser in response to user interactions or effects.
```tsx import { useNavigate } from "react-router";
function SomeComponent() { let navigate = useNavigate(); return ( <button onClick={() => { navigate(-1); }} /> ); } ```
It's often better to use redirect in actions and loaders than this hook.
Hooks
function useNavigation
useNavigation: () => Navigation;
Returns the current navigation, defaulting to an "idle" navigation when no navigation is in progress. You can use this to render pending UI (like a global spinner) or read FormData from a form navigation.
```tsx import { useNavigation } from "react-router"
function SomeComponent() { let navigation = useNavigation(); navigation.state navigation.formData // etc. } ```
Hooks
function useNavigationType
useNavigationType: () => Action;
Returns the current navigation action which describes how the router came to the current location, either by a pop, push, or replace on the history stack.
Hooks
function useOutlet
useOutlet: (context?: unknown) => React.ReactElement | null;
Returns the element for the child route at this level of the route hierarchy. Used internally by
<Outlet>
to render child routes.Hooks
function useOutletContext
useOutletContext: <Context = unknown>() => Context;
Returns the parent route `<Outlet context>`.
Hooks
function useParams
useParams: < ParamsOrKey extends string | Record<string, string> = string>() => Readonly< [ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>>;
Returns an object of key/value pairs of the dynamic params from the current URL that were matched by the routes. Child routes inherit all params from their parent routes.
```tsx import { useParams } from "react-router"
function SomeComponent() { let params = useParams() params.postId } ```
Assuming a route pattern like
/posts/:postId
is matched by/posts/123
thenparams.postId
will be"123"
.Hooks
function useResolvedPath
useResolvedPath: ( to: To, { relative }?: { relative?: RelativeRoutingType }) => Path;
Resolves the pathname of the given
to
value against the current location. Similar to useHref, but returns a Path instead of a string.```tsx import { useResolvedPath } from "react-router"
function SomeComponent() { // if the user is at /dashboard/profile let path = useResolvedPath("../accounts") path.pathname // "/dashboard/accounts" path.search // "" path.hash // "" } ```
Hooks
function useRevalidator
useRevalidator: () => { revalidate(): Promise<void>; state: RevalidationState };
Revalidate the data on the page for reasons outside of normal data mutations like window focus or polling on an interval.
```tsx import { useRevalidator } from "react-router";
function WindowFocusRevalidator() { const revalidator = useRevalidator();
useFakeWindowFocus(() => { revalidator.revalidate(); });
return ( <div hidden={revalidator.state === "idle"}> Revalidating... ); } ```
Note that page data is already revalidated automatically after actions. If you find yourself using this for normal CRUD operations on your data in response to user interactions, you're probably not taking advantage of the other APIs like useFetcher, Form, useSubmit that do this automatically.
Hooks
function useRouteError
useRouteError: () => unknown;
function useRouteLoaderData
useRouteLoaderData: <T = any>(routeId: string) => SerializeFrom<T> | undefined;
Returns the loader data for a given route by route ID.
```tsx import { useRouteLoaderData } from "react-router";
function SomeComponent() { const { user } = useRouteLoaderData("root"); } ```
Route IDs are created automatically. They are simply the path of the route file relative to the app folder without the extension.
| Route Filename | Route ID | | -------------------------- | -------------------- | |
app/root.tsx
|"root"
| |app/routes/teams.tsx
|"routes/teams"
| |app/whatever/teams.$id.tsx
|"whatever/teams.$id"
|If you created an ID manually, you can use that instead:
```tsx route("/", "containers/app.tsx", { id: "app" }}) ```
Hooks
function useRoutes
useRoutes: ( routes: RouteObject[], locationArg?: Partial<Location> | string) => React.ReactElement | null;
Hook version of `<Routes>` that uses objects instead of components. These objects have the same properties as the component props.
The return value of
useRoutes
is either a valid React element you can use to render the route tree, ornull
if nothing matched.```tsx import * as React from "react"; import { useRoutes } from "react-router";
function App() { let element = useRoutes([ { path: "/", element: , children: [ { path: "messages", element: , }, { path: "tasks", element: }, ], }, { path: "team", element: }, ]);
return element; } ```
Hooks
function useSearchParams
useSearchParams: ( defaultInit?: URLSearchParamsInit) => [URLSearchParams, SetURLSearchParams];
Returns a tuple of the current URL's URLSearchParams and a function to update them. Setting the search params causes a navigation.
```tsx import { useSearchParams } from "react-router";
export function SomeComponent() { const [searchParams, setSearchParams] = useSearchParams(); // ... } ```
Hooks
function useSubmit
useSubmit: () => SubmitFunction;
The imperative version of `<Form>` that lets you submit a form from code instead of a user interaction.
```tsx import { useSubmit } from "react-router";
function SomeComponent() { const submit = useSubmit(); return ( <Form onChange={(event) => { submit(event.currentTarget); }} /> ); } ```
Hooks
function useViewTransitionState
useViewTransitionState: ( to: To, opts?: { relative?: RelativeRoutingType }) => boolean;
This hook returns
true
when there is an active [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) to the specified location. This can be used to apply finer-grained styles to elements to further customize the view transition. This requires that view transitions have been enabled for the given navigation via LinkProps.viewTransition (or theForm
,submit
, ornavigate
call)Hooks useViewTransitionState
Classes
class UNSAFE_DataWithResponseInit
class DataWithResponseInit<D> {}
constructor
constructor(data: {}, init?: ResponseInit);
property data
data: {};
property init
init: ResponseInit;
property type
type: string;
class UNSAFE_ErrorResponseImpl
class ErrorResponseImpl implements ErrorResponse {}
Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies
We don't export the class for public use since it's an implementation detail, but we export the interface above so folks can build their own abstractions around instances via isRouteErrorResponse()
constructor
constructor(status: number, statusText: string, data: any, internal?: boolean);
property data
data: any;
property status
status: number;
property statusText
statusText: string;
class UNSAFE_RemixErrorBoundary
class RemixErrorBoundary extends React.Component< RemixErrorBoundaryProps, RemixErrorBoundaryState> {}
constructor
constructor( props: React.PropsWithChildren<{ location: Location<any>; isOutsideRemixApp?: boolean; error?: Error; }>);
method getDerivedStateFromError
static getDerivedStateFromError: (error: Error) => { error: Error };
method getDerivedStateFromProps
static getDerivedStateFromProps: ( props: React.PropsWithChildren<{ location: Location<any>; isOutsideRemixApp?: boolean; error?: Error; }>, state: RemixErrorBoundaryState) => { error: Error | null; location: Location<any> };
method render
render: () => | string | number | boolean | Iterable<React.ReactNode> | React.JSX.Element | null | undefined;
Interfaces
interface ActionFunction
interface ActionFunction<Context = any> {}
Route action function signature
call signature
( args: ActionFunctionArgs<Context>, handlerCtx?: unknown): DataFunctionReturnValue;
interface ActionFunctionArgs
interface ActionFunctionArgs<Context = any> extends DataFunctionArgs<Context> {}
Arguments passed to action functions
interface AppLoadContext
interface AppLoadContext {}
An object of unknown type for route loaders and actions provided by the server's
getLoadContext()
function. This is defined as an empty interface specifically so apps can leverage declaration merging to augment this type globally: https://www.typescriptlang.org/docs/handbook/declaration-merging.html
index signature
[key: string]: unknown;
interface AwaitProps
interface AwaitProps<Resolve> {}
Types
property children
children: React.ReactNode | AwaitResolveRenderFunction<Resolve>;
When using a function, the resolved value is provided as the parameter.
```tsx [2] <Await resolve={reviewsPromise}> {(resolvedReviews) => <Reviews items={resolvedReviews} />} ```
When using React elements, useAsyncValue will provide the resolved value:
```tsx [2] <Await resolve={reviewsPromise}>
function Reviews() { const resolvedReviews = useAsyncValue() return ... } ```
property errorElement
errorElement?: React.ReactNode;
The error element renders instead of the children when the promise rejects.
```tsx <Await errorElement={Oops} resolve={reviewsPromise} > ```
To provide a more contextual error, you can use the useAsyncError in a child component
```tsx <Await errorElement={} resolve={reviewsPromise} >
function ReviewsError() { const error = useAsyncError() return Error loading reviews: {error.message} } ```
If you do not provide an errorElement, the rejected value will bubble up to the nearest route-level ErrorBoundary and be accessible via useRouteError hook.
property resolve
resolve: Resolve;
Takes a promise returned from a loader value to be resolved and rendered.
```jsx import { useLoaderData, Await } from "react-router"
export async function loader() { let reviews = getReviews() // not awaited let book = await getBook() return { book, reviews, // this is a promise } }
export default function Book() { const { book, reviews, // this is the same promise } = useLoaderData()
return ( {book.title} {book.description} <React.Suspense fallback={}> <Await // and is the promise we pass to Await resolve={reviews} > </React.Suspense> ); } ```
interface BrowserRouterProps
interface BrowserRouterProps {}
Types
interface Cookie
interface Cookie {}
A HTTP cookie.
A Cookie is a logical container for metadata about a HTTP cookie; its name and options. But it doesn't contain a value. Instead, it has
parse()
andserialize()
methods that allow a single instance to be reused for parsing/encoding multiple different values.See Also
https://remix.run/utils/cookies#cookie-api
property expires
readonly expires?: Date;
The Date this cookie expires.
Note: This is calculated at access time using
maxAge
when noexpires
option is provided tocreateCookie()
.
property isSigned
readonly isSigned: boolean;
True if this cookie uses one or more secrets for verification.
property name
readonly name: string;
The name of the cookie, used in the
Cookie
andSet-Cookie
headers.
method parse
parse: (cookieHeader: string | null, options?: ParseOptions) => Promise<any>;
Parses a raw
Cookie
header and returns the value of this cookie ornull
if it's not present.
method serialize
serialize: (value: any, options?: SerializeOptions) => Promise<string>;
Serializes the given value to a string and returns the
Set-Cookie
header.
interface CookieSignatureOptions
interface CookieSignatureOptions {}
property secrets
secrets?: string[];
An array of secrets that may be used to sign/unsign the value of a cookie.
The array makes it easy to rotate secrets. New secrets should be added to the beginning of the array.
cookie.serialize()
will always use the first value in the array, butcookie.parse()
may use any of them so that cookies that were signed with older secrets still work.
interface DataRouteMatch
interface DataRouteMatch extends RouteMatch<string, DataRouteObject> {}
interface DataRouter
interface Router {}
A Router instance manages all navigation and data loading/mutations
method createHref
createHref: (location: Location | URL) => string;
PRIVATE - DO NOT USE
Utility function to create an href for the given location
Parameter location
method deleteBlocker
deleteBlocker: (key: string) => void;
PRIVATE - DO NOT USE
Delete a navigation blocker
Parameter key
The identifier for the blocker
method deleteFetcher
deleteFetcher: (key: string) => void;
PRIVATE - DO NOT USE
Delete the fetcher for a given key
Parameter key
method dispose
dispose: () => void;
PRIVATE - DO NOT USE
Cleanup listeners and abort any in-progress loads
method enableScrollRestoration
enableScrollRestoration: ( savedScrollPositions: Record<string, number>, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction) => () => void;
PRIVATE - DO NOT USE
Enable scroll restoration behavior in the router
Parameter savedScrollPositions
Object that will manage positions, in case it's being restored from sessionStorage
Parameter getScrollPosition
Function to get the active Y scroll position
Parameter getKey
Function to get the key to use for restoration
method encodeLocation
encodeLocation: (to: To) => Path;
PRIVATE - DO NOT USE
Utility function to URL encode a destination path according to the internal history implementation
Parameter to
method fetch
fetch: ( key: string, routeId: string, href: string | null, opts?: RouterFetchOptions) => Promise<void>;
PRIVATE - DO NOT USE
Trigger a fetcher load/submission
Parameter key
Fetcher key
Parameter routeId
Route that owns the fetcher
Parameter href
href to fetch
Parameter opts
Fetcher options, (method, submission, etc.)
method getBlocker
getBlocker: (key: string, fn: BlockerFunction) => Blocker;
PRIVATE - DO NOT USE
Get a navigation blocker
Parameter key
The identifier for the blocker
Parameter fn
The blocker function implementation
method getFetcher
getFetcher: <TData = any>(key: string) => Fetcher<TData>;
PRIVATE - DO NOT USE
Get/create a fetcher for the given key
Parameter key
method initialize
initialize: () => Router;
PRIVATE - DO NOT USE
Initialize the router, including adding history listeners and kicking off initial data fetches. Returns a function to cleanup listeners and abort any in-progress loads
method navigate
navigate: { (to: number): Promise<void>; (to: To, opts?: RouterNavigateOptions): Promise<void>;};
PRIVATE - DO NOT USE
Navigate forward/backward in the history stack
Parameter to
Delta to move in the history stack
Navigate to the given path
Parameter to
Path to navigate to
Parameter opts
Navigation options (method, submission, etc.)
method patchRoutes
patchRoutes: (routeId: string | null, children: AgnosticRouteObject[]) => void;
PRIVATE DO NOT USE
Patch additional children routes into an existing parent route
Parameter routeId
The parent route id or a callback function accepting
patch
to perform batch patchingParameter children
The additional children routes
method revalidate
revalidate: () => Promise<void>;
PRIVATE - DO NOT USE
Trigger a revalidation of all current route loaders and fetcher loads
method subscribe
subscribe: (fn: RouterSubscriber) => () => void;
PRIVATE - DO NOT USE
Subscribe to router.state updates
Parameter fn
function to call with the new state
index signature
get basename(): RouterInit['basename'];
PRIVATE - DO NOT USE
Return the basename for the router
index signature
get future(): FutureConfig;
PRIVATE - DO NOT USE
Return the future config for the router
index signature
get state(): RouterState;
PRIVATE - DO NOT USE
Return the current state of the router
index signature
get routes(): AgnosticDataRouteObject[];
PRIVATE - DO NOT USE
Return the routes for this router instance
index signature
get window(): RouterInit['window'];
PRIVATE - DO NOT USE
Return the window associated with the router
interface DataStrategyFunction
interface DataStrategyFunction {}
call signature
(args: DataStrategyFunctionArgs): Promise<Record<string, DataStrategyResult>>;
interface DataStrategyFunctionArgs
interface DataStrategyFunctionArgs<Context = any> extends DataFunctionArgs<Context> {}
property fetcherKey
fetcherKey: string | null;
property matches
matches: DataStrategyMatch[];
interface DataStrategyMatch
interface DataStrategyMatch extends AgnosticRouteMatch<string, AgnosticDataRouteObject> {}
property resolve
resolve: ( handlerOverride?: ( handler: (ctx?: unknown) => DataFunctionReturnValue ) => DataFunctionReturnValue) => Promise<DataStrategyResult>;
property shouldLoad
shouldLoad: boolean;
interface DataStrategyResult
interface DataStrategyResult {}
Result from a loader or action called via dataStrategy
interface EntryContext
interface EntryContext extends FrameworkContextObject {}
property serverHandoffStream
serverHandoffStream?: ReadableStream<Uint8Array>;
property staticHandlerContext
staticHandlerContext: StaticHandlerContext;
interface FetcherFormProps
interface FetcherFormProps extends SharedFormProps {}
Form props available to fetchers Types
interface FetcherSubmitFunction
interface FetcherSubmitFunction {}
Submits a fetcher
<form>
to the server without reloading the page.
call signature
( /** Can be multiple types of elements and objects
**`HTMLFormElement`**
```tsx <fetcher.Form onSubmit={(event) => { fetcher.submit(event.currentTarget); }} /> ```
**`FormData`**
```tsx const formData = new FormData(); formData.append("myKey", "myValue"); fetcher.submit(formData, { method: "post" }); ```
**Plain object that will be serialized as `FormData`**
```tsx fetcher.submit({ myKey: "myValue" }, { method: "post" }); ```
**Plain object that will be serialized as JSON**
```tsx fetcher.submit( { myKey: "myValue" }, { method: "post", encType: "application/json" } ); ```
*/ target: SubmitTarget, options?: FetcherSubmitOptions): Promise<void>;
interface FetcherSubmitOptions
interface FetcherSubmitOptions extends SharedSubmitOptions {}
Submit options available to fetchers
interface FormProps
interface FormProps extends SharedFormProps {}
Form props available to navigations Types
property discover
discover?: DiscoverBehavior;
property fetcherKey
fetcherKey?: string;
Indicates a specific fetcherKey to use when using
navigate={false}
so you can pick up the fetcher's state in a different component in a useFetcher.
property navigate
navigate?: boolean;
Skips the navigation and uses a fetcher internally when
false
. This is essentially a shorthand foruseFetcher()
+<fetcher.Form>
where you don't care about the resulting data in this component.
property reloadDocument
reloadDocument?: boolean;
Forces a full document navigation instead of client side routing + data fetch.
property replace
replace?: boolean;
Replaces the current entry in the browser history stack when the form navigates. Use this if you don't want the user to be able to click "back" to the page with the form on it.
property state
state?: any;
State object to add to the history stack entry for this navigation
property viewTransition
viewTransition?: boolean;
Enables a [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) for this navigation. To apply specific styles during the transition see useViewTransitionState.
interface GetScrollPositionFunction
interface GetScrollPositionFunction {}
Function signature for determining the current scroll position
call signature
(): number;
interface GetScrollRestorationKeyFunction
interface GetScrollRestorationKeyFunction {}
Function signature for determining the key to be used in scroll restoration for a given location
call signature
(location: Location, matches: UIMatch[]): string | null;
interface HandleDataRequestFunction
interface HandleDataRequestFunction {}
call signature
(response: Response, args: LoaderFunctionArgs | ActionFunctionArgs): | Promise<Response> | Response;
interface HandleDocumentRequestFunction
interface HandleDocumentRequestFunction {}
call signature
( request: Request, responseStatusCode: number, responseHeaders: Headers, context: EntryContext, loadContext: AppLoadContext$1): Promise<Response> | Response;
interface HandleErrorFunction
interface HandleErrorFunction {}
call signature
(error: unknown, args: LoaderFunctionArgs | ActionFunctionArgs): void;
interface HashRouterProps
interface HashRouterProps {}
Types
interface HeadersFunction
interface HeadersFunction {}
A function that returns HTTP headers to be used for a route. These headers will be merged with (and take precedence over) headers from parent routes.
call signature
(args: HeadersArgs): Headers | HeadersInit;
interface HistoryRouterProps
interface HistoryRouterProps {}
Types
interface IndexRouteObject
interface IndexRouteObject {}
property action
action?: AgnosticIndexRouteObject['action'];
property caseSensitive
caseSensitive?: AgnosticIndexRouteObject['caseSensitive'];
property children
children?: undefined;
property Component
Component?: React.ComponentType | null;
property element
element?: React.ReactNode | null;
property ErrorBoundary
ErrorBoundary?: React.ComponentType | null;
property errorElement
errorElement?: React.ReactNode | null;
property handle
handle?: AgnosticIndexRouteObject['handle'];
property hasErrorBoundary
hasErrorBoundary?: AgnosticIndexRouteObject['hasErrorBoundary'];
property HydrateFallback
HydrateFallback?: React.ComponentType | null;
property hydrateFallbackElement
hydrateFallbackElement?: React.ReactNode | null;
property id
id?: AgnosticIndexRouteObject['id'];
property index
index: true;
property lazy
lazy?: LazyRouteFunction<RouteObject>;
property loader
loader?: AgnosticIndexRouteObject['loader'];
property path
path?: AgnosticIndexRouteObject['path'];
property shouldRevalidate
shouldRevalidate?: AgnosticIndexRouteObject['shouldRevalidate'];
interface IndexRouteProps
interface IndexRouteProps {}
Types
property action
action?: IndexRouteObject['action'];
property caseSensitive
caseSensitive?: IndexRouteObject['caseSensitive'];
property children
children?: undefined;
property Component
Component?: React.ComponentType | null;
property element
element?: React.ReactNode | null;
property ErrorBoundary
ErrorBoundary?: React.ComponentType | null;
property errorElement
errorElement?: React.ReactNode | null;
property handle
handle?: IndexRouteObject['handle'];
property hasErrorBoundary
hasErrorBoundary?: IndexRouteObject['hasErrorBoundary'];
property HydrateFallback
HydrateFallback?: React.ComponentType | null;
property hydrateFallbackElement
hydrateFallbackElement?: React.ReactNode | null;
property id
id?: IndexRouteObject['id'];
property index
index: true;
property lazy
lazy?: LazyRouteFunction<IndexRouteObject>;
property loader
loader?: IndexRouteObject['loader'];
property path
path?: IndexRouteObject['path'];
property shouldRevalidate
shouldRevalidate?: IndexRouteObject['shouldRevalidate'];
interface LayoutRouteProps
interface LayoutRouteProps extends PathRouteProps {}
Types
interface LazyRouteFunction
interface LazyRouteFunction<R extends AgnosticRouteObject> {}
lazy() function to load a route definition, which can add non-matching related properties to a route
call signature
(): Promise<RequireOne<Omit<R, ImmutableRouteKey>>>;
interface LinkProps
interface LinkProps extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> {}
Types
property discover
discover?: DiscoverBehavior;
Defines the link discovery behavior
```tsx // default ("render") ```
- **render** - default, discover the route when the link renders - **none** - don't eagerly discover, only discover if the link is clicked
property prefetch
prefetch?: PrefetchBehavior;
Defines the data and module prefetching behavior for the link.
```tsx // default ```
- **none** - default, no prefetching - **intent** - prefetches when the user hovers or focuses the link - **render** - prefetches when the link renders - **viewport** - prefetches when the link is in the viewport, very useful for mobile
Prefetching is done with HTML
<link rel="prefetch">
tags. They are inserted after the link.```tsx // might conditionally render ```
Because of this, if you are using
nav :last-child
you will need to usenav :last-of-type
so the styles don't conditionally fall off your last link (and any other similar selectors).
property preventScrollReset
preventScrollReset?: boolean;
Prevents the scroll position from being reset to the top of the window when the link is clicked and the app is using ScrollRestoration. This only prevents new locations reseting scroll to the top, scroll position will be restored for back/forward button navigation.
```tsx <Link to="?tab=one" preventScrollReset /> ```
property relative
relative?: RelativeRoutingType;
Defines the relative path behavior for the link.
```tsx // default: "route" ```
Consider a route hierarchy where a parent route pattern is "blog" and a child route pattern is "blog/:slug/edit".
- **route** - default, resolves the link relative to the route pattern. In the example above a relative link of
".."
will remove both:slug/edit
segments back to "/blog". - **path** - relative to the path so..
will only remove one URL segment up to "/blog/:slug"
property reloadDocument
reloadDocument?: boolean;
Will use document navigation instead of client side routing when the link is clicked: the browser will handle the transition normally (as if it were an
<a href>
).```tsx <Link to="/logout" reloadDocument /> ```
property replace
replace?: boolean;
Replaces the current entry in the history stack instead of pushing a new one onto it.
```tsx <Link replace /> ```
``` # with a history stack like this A -> B
# normal link click pushes a new entry A -> B -> C
# but with
replace
, B is replaced by C A -> C ```
property state
state?: any;
Adds persistent client side routing state to the next location.
```tsx <Link to="/somewhere/else" state={{ some: "value" }} /> ```
The location state is accessed from the
location
.```tsx function SomeComp() { const location = useLocation() location.state; // { some: "value" } } ```
This state is inaccessible on the server as it is implemented on top of [
history.state
](https://developer.mozilla.org/en-US/docs/Web/API/History/state)
property to
to: To;
Can be a string or a partial Path:
```tsx
<Link to={{ pathname: "/some/path", search: "?query=string", hash: "#hash", }} /> ```
property viewTransition
viewTransition?: boolean;
Enables a [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) for this navigation.
```jsx <Link to={to} viewTransition> Click me ```
To apply specific styles for the transition, see useViewTransitionState
interface LinksFunction
interface LinksFunction {}
A function that defines
<link>
tags to be inserted into the<head>
of the document on route transitions.See Also
https://remix.run/route/meta
call signature
(): LinkDescriptor[];
interface LoaderFunctionArgs
interface LoaderFunctionArgs<Context = any> extends DataFunctionArgs<Context> {}
Arguments passed to loader functions
interface Location
interface Location<State = any> extends Path {}
An entry in a history stack. A location contains information about the URL path, as well as possibly some arbitrary state and a key.
property key
key: string;
A unique string associated with this location. May be used to safely store and retrieve data in some other storage API, like
localStorage
.Note: This value is always "default" on the initial location.
property state
state: State;
A value of arbitrary data associated with this location.
interface MemoryRouterProps
interface MemoryRouterProps {}
Types
property basename
basename?: string;
property children
children?: React.ReactNode;
property initialEntries
initialEntries?: InitialEntry[];
property initialIndex
initialIndex?: number;
interface MetaArgs
interface MetaArgs< Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record< string, LoaderFunction | ClientLoaderFunction | unknown > = Record<string, unknown>> {}
interface MetaFunction
interface MetaFunction< Loader extends LoaderFunction | ClientLoaderFunction | unknown = unknown, MatchLoaders extends Record< string, LoaderFunction | ClientLoaderFunction | unknown > = Record<string, unknown>> {}
A function that returns an array of data objects to use for rendering metadata HTML tags in a route. These tags are not rendered on descendant routes in the route hierarchy. In other words, they will only be rendered on the route in which they are exported.
Parameter Loader
The type of the current route's loader function
Parameter MatchLoaders
Mapping from a parent route's filepath to its loader function type
Note that parent route filepaths are relative to the
app/
directory.For example, if this meta function is for
/sales/customers/$customerId
:// app/root.tsxconst loader = () => ({ hello: "world" })export type Loader = typeof loader// app/routes/sales.tsxconst loader = () => ({ salesCount: 1074 })export type Loader = typeof loader// app/routes/sales/customers.tsxconst loader = () => ({ customerCount: 74 })export type Loader = typeof loader// app/routes/sales/customers/$customersId.tsximport type { Loader as RootLoader } from "../../../root"import type { Loader as SalesLoader } from "../../sales"import type { Loader as CustomersLoader } from "../../sales/customers"const loader = () => ({ name: "Customer name" })const meta: MetaFunction<typeof loader, {"root": RootLoader,"routes/sales": SalesLoader,"routes/sales/customers": CustomersLoader,}> = ({ data, matches }) => {const { name } = data// ^? stringconst { customerCount } = matches.find((match) => match.id === "routes/sales/customers").data// ^? numberconst { salesCount } = matches.find((match) => match.id === "routes/sales").data// ^? numberconst { hello } = matches.find((match) => match.id === "root").data// ^? "world"}
call signature
(args: MetaArgs<Loader, MatchLoaders>): MetaDescriptor[] | undefined;
interface NavigateFunction
interface NavigateFunction {}
The interface for the navigate() function returned from useNavigate().
call signature
(to: To, options?: NavigateOptions): void | Promise<void>;
call signature
(delta: number): void | Promise<void>;
interface NavigateOptions
interface NavigateOptions {}
property flushSync
flushSync?: boolean;
property preventScrollReset
preventScrollReset?: boolean;
property relative
relative?: RelativeRoutingType;
property replace
replace?: boolean;
property state
state?: any;
property viewTransition
viewTransition?: boolean;
interface NavigateProps
interface NavigateProps {}
Types
interface Navigator
interface Navigator {}
A Navigator is a "location changer"; it's how you get to different locations.
Every history instance conforms to the Navigator interface, but the distinction is useful primarily when it comes to the low-level
<Router>
API where both the location and a navigator must be provided separately in order to avoid "tearing" that may occur in a suspense-enabled app if the action and/or location were to be read directly from the history instance.
property createHref
createHref: History['createHref'];
property encodeLocation
encodeLocation?: History['encodeLocation'];
property go
go: History['go'];
method push
push: (to: To, state?: any, opts?: NavigateOptions) => void;
method replace
replace: (to: To, state?: any, opts?: NavigateOptions) => void;
interface NavLinkProps
interface NavLinkProps extends Omit<LinkProps, 'className' | 'style' | 'children'> {}
Types
property caseSensitive
caseSensitive?: boolean;
Changes the matching logic to make it case-sensitive:
| Link | URL | isActive | | -------------------------------------------- | ------------- | -------- | |
<NavLink to="/SpOnGe-bOB" />
|/sponge-bob
| true | |<NavLink to="/SpOnGe-bOB" caseSensitive />
|/sponge-bob
| false |
property children
children?: React.ReactNode | ((props: NavLinkRenderProps) => React.ReactNode);
Can be regular React children or a function that receives an object with the active and pending states of the link.
```tsx {({ isActive }) => ( <span className={isActive ? "active" : ""}>Tasks )} ```
property className
className?: string | ((props: NavLinkRenderProps) => string | undefined);
Classes are automatically applied to NavLink that correspond to NavLinkRenderProps.
```css a.active { color: red; } a.pending { color: blue; } a.transitioning { view-transition-name: my-transition; } ```
property end
end?: boolean;
Changes the matching logic for the
active
andpending
states to only match to the "end" of the NavLinkProps.to. If the URL is longer, it will no longer be considered active.| Link | URL | isActive | | ----------------------------- | ------------ | -------- | |
<NavLink to="/tasks" />
|/tasks
| true | |<NavLink to="/tasks" />
|/tasks/123
| true | |<NavLink to="/tasks" end />
|/tasks
| true | |<NavLink to="/tasks" end />
|/tasks/123
| false |<NavLink to="/">
is an exceptional case because _every_ URL matches/
. To avoid this matching every single route by default, it effectively ignores theend
prop and only matches when you're at the root route.
property style
style?: | React.CSSProperties | ((props: NavLinkRenderProps) => React.CSSProperties | undefined);
interface NonIndexRouteObject
interface NonIndexRouteObject {}
property action
action?: AgnosticNonIndexRouteObject['action'];
property caseSensitive
caseSensitive?: AgnosticNonIndexRouteObject['caseSensitive'];
property children
children?: RouteObject[];
property Component
Component?: React.ComponentType | null;
property element
element?: React.ReactNode | null;
property ErrorBoundary
ErrorBoundary?: React.ComponentType | null;
property errorElement
errorElement?: React.ReactNode | null;
property handle
handle?: AgnosticNonIndexRouteObject['handle'];
property hasErrorBoundary
hasErrorBoundary?: AgnosticNonIndexRouteObject['hasErrorBoundary'];
property HydrateFallback
HydrateFallback?: React.ComponentType | null;
property hydrateFallbackElement
hydrateFallbackElement?: React.ReactNode | null;
property id
id?: AgnosticNonIndexRouteObject['id'];
property index
index?: false;
property lazy
lazy?: LazyRouteFunction<RouteObject>;
property loader
loader?: AgnosticNonIndexRouteObject['loader'];
property path
path?: AgnosticNonIndexRouteObject['path'];
property shouldRevalidate
shouldRevalidate?: AgnosticNonIndexRouteObject['shouldRevalidate'];
interface OutletProps
interface OutletProps {}
Types
property context
context?: unknown;
Provides a context value to the element tree below the outlet. Use when the parent route needs to provide values to child routes.
```tsx <Outlet context={myContextValue} /> ```
Access the context with useOutletContext.
interface PageLinkDescriptor
interface PageLinkDescriptor extends Omit< HtmlLinkDescriptor, | 'href' | 'rel' | 'type' | 'sizes' | 'imageSrcSet' | 'imageSizes' | 'as' | 'color' | 'title' > {}
property page
page: string;
The absolute path of the page to prefetch.
interface Path
interface Path {}
The pathname, search, and hash values of a URL.
interface PathMatch
interface PathMatch<ParamKey extends string = string> {}
A PathMatch contains info about how a PathPattern matched on a URL pathname.
property params
params: Params<ParamKey>;
The names and values of dynamic parameters in the URL.
property pathname
pathname: string;
The portion of the URL pathname that was matched.
property pathnameBase
pathnameBase: string;
The portion of the URL pathname that was matched before child routes.
property pattern
pattern: PathPattern;
The pattern that was used to match.
interface PathPattern
interface PathPattern<Path extends string = string> {}
A PathPattern is used to match on some portion of a URL pathname.
property caseSensitive
caseSensitive?: boolean;
Should be
true
if the static portions of thepath
should be matched in the same case.
property end
end?: boolean;
Should be
true
if this pattern should match the entire URL pathname.
property path
path: Path;
A string to match against a URL pathname. May contain
:id
-style segments to indicate placeholders for dynamic parameters. May also end with/*
to indicate matching the rest of the URL pathname.
interface PathRouteProps
interface PathRouteProps {}
Types
property action
action?: NonIndexRouteObject['action'];
property caseSensitive
caseSensitive?: NonIndexRouteObject['caseSensitive'];
property children
children?: React.ReactNode;
property Component
Component?: React.ComponentType | null;
property element
element?: React.ReactNode | null;
property ErrorBoundary
ErrorBoundary?: React.ComponentType | null;
property errorElement
errorElement?: React.ReactNode | null;
property handle
handle?: NonIndexRouteObject['handle'];
property hasErrorBoundary
hasErrorBoundary?: NonIndexRouteObject['hasErrorBoundary'];
property HydrateFallback
HydrateFallback?: React.ComponentType | null;
property hydrateFallbackElement
hydrateFallbackElement?: React.ReactNode | null;
property id
id?: NonIndexRouteObject['id'];
property index
index?: false;
property lazy
lazy?: LazyRouteFunction<NonIndexRouteObject>;
property loader
loader?: NonIndexRouteObject['loader'];
property path
path?: NonIndexRouteObject['path'];
property shouldRevalidate
shouldRevalidate?: NonIndexRouteObject['shouldRevalidate'];
interface RouteMatch
interface RouteMatch< ParamKey extends string = string, RouteObjectType extends RouteObject = RouteObject> extends AgnosticRouteMatch<ParamKey, RouteObjectType> {}
interface RouterInit
interface RouterInit {}
Initialization options for createRouter
property basename
basename?: string;
property dataStrategy
dataStrategy?: DataStrategyFunction;
property future
future?: Partial<FutureConfig>;
property history
history: History;
property hydrationData
hydrationData?: HydrationState;
property mapRouteProperties
mapRouteProperties?: MapRoutePropertiesFunction;
property patchRoutesOnNavigation
patchRoutesOnNavigation?: AgnosticPatchRoutesOnNavigationFunction;
property routes
routes: AgnosticRouteObject[];
property window
window?: Window;
interface RouterProps
interface RouterProps {}
Types
interface RouterProviderProps
interface RouterProviderProps {}
interface RouterState
interface RouterState {}
State maintained internally by the router. During a navigation, all states reflect the the "old" location unless otherwise noted.
property actionData
actionData: RouteData | null;
Data from the action for the current matches
property blockers
blockers: Map<string, Blocker>;
Map of current blockers
property errors
errors: RouteData | null;
Errors caught from loaders for the current matches
property fetchers
fetchers: Map<string, Fetcher>;
Map of current fetchers
property historyAction
historyAction: Action;
The action of the most recent navigation
property initialized
initialized: boolean;
Tracks whether we've completed our initial data load
property loaderData
loaderData: RouteData;
Data from the loaders for the current matches
property location
location: Location;
The current location reflected by the router
property matches
matches: AgnosticDataRouteMatch[];
The current set of route matches
property navigation
navigation: Navigation;
Tracks the state of the current navigation
property preventScrollReset
preventScrollReset: boolean;
Indicate whether this navigation should skip resetting the scroll position if we are unable to restore the scroll position
property restoreScrollPosition
restoreScrollPosition: number | false | null;
Current scroll position we should start at for a new view - number -> scroll position to restore to - false -> do not restore scroll at all (used during submissions) - null -> don't have a saved position, scroll to hash or top of page
property revalidation
revalidation: RevalidationState;
Tracks any in-progress revalidations
interface RouterSubscriber
interface RouterSubscriber {}
Subscriber function signature for changes to router state
call signature
( state: RouterState, opts: { deletedFetchers: string[]; viewTransitionOpts?: ViewTransitionOpts; flushSync: boolean; }): void;
interface RoutesProps
interface RoutesProps {}
Types
interface RoutesTestStubProps
interface RoutesTestStubProps {}
property future
future?: Partial<FutureConfig>;
Future flags mimicking the settings in react-router.config.ts
property hydrationData
hydrationData?: HydrationState;
Used to set the route's initial loader and action data. e.g. hydrationData={{ loaderData: { "/contact": { locale: "en-US" } }, actionData: { "/login": { errors: { email: "invalid email" } }} }}
property initialEntries
initialEntries?: InitialEntry[];
The initial entries in the history stack. This allows you to start a test with multiple locations already in the history stack (for testing a back navigation, etc.) The test will default to the last entry in initialEntries if no initialIndex is provided. e.g. initialEntries={["/home", "/about", "/contact"]}
property initialIndex
initialIndex?: number;
The initial index in the history stack to render. This allows you to start a test at a specific entry. It defaults to the last entry in initialEntries. e.g. initialEntries: ["/", "/events/123"] initialIndex: 1 // start at "/events/123"
interface ServerBuild
interface ServerBuild {}
The output of the compiler for the server build.
property assets
assets: AssetsManifest;
property assetsBuildDirectory
assetsBuildDirectory: string;
property basename
basename?: string;
property entry
entry: { module: ServerEntryModule;};
property future
future: FutureConfig;
property isSpaMode
isSpaMode: boolean;
property publicPath
publicPath: string;
property routes
routes: ServerRouteManifest;
interface ServerEntryModule
interface ServerEntryModule {}
A module that serves as the entry point for a Remix app during server rendering.
property default
default: HandleDocumentRequestFunction;
property handleDataRequest
handleDataRequest?: HandleDataRequestFunction;
property handleError
handleError?: HandleErrorFunction;
property streamTimeout
streamTimeout?: number;
interface ServerRouterProps
interface ServerRouterProps {}
property abortDelay
abortDelay?: number;
property context
context: EntryContext;
property nonce
nonce?: string;
property url
url: string | URL;
interface Session
interface Session<Data = SessionData, FlashData = Data> {}
Session persists data across HTTP requests.
See Also
https://remix.run/utils/sessions#session-api
property data
readonly data: FlashSessionData<Data, FlashData>;
The raw data contained in this session.
This is useful mostly for SessionStorage internally to access the raw session data to persist.
property id
readonly id: string;
A unique identifier for this session.
Note: This will be the empty string for newly created sessions and sessions that are not backed by a database (i.e. cookie-based sessions).
method flash
flash: <Key extends keyof FlashData & string>( name: Key, value: FlashData[Key]) => void;
Sets a value in the session that is only valid until the next
get()
. This can be useful for temporary values, like error messages.
method get
get: <Key extends (keyof FlashData | keyof Data) & string>( name: Key) => | (Key extends keyof Data ? Data[Key] : undefined) | (Key extends keyof FlashData ? FlashData[Key] : undefined) | undefined;
Returns the value for the given
name
in this session.
method has
has: (name: (keyof Data | keyof FlashData) & string) => boolean;
Returns
true
if the session has a value for the givenname
,false
otherwise.
method set
set: <Key extends keyof Data & string>(name: Key, value: Data[Key]) => void;
Sets a value in the session for the given
name
.
method unset
unset: (name: keyof Data & string) => void;
Removes a value from the session.
interface SessionData
interface SessionData {}
An object of name/value pairs to be used in the session.
index signature
[name: string]: any;
interface SessionIdStorageStrategy
interface SessionIdStorageStrategy<Data = SessionData, FlashData = Data> {}
SessionIdStorageStrategy is designed to allow anyone to easily build their own SessionStorage using
createSessionStorage(strategy)
.This strategy describes a common scenario where the session id is stored in a cookie but the actual session data is stored elsewhere, usually in a database or on disk. A set of create, read, update, and delete operations are provided for managing the session data.
property cookie
cookie?: | Cookie | (CookieOptions & { name?: string; });
The Cookie used to store the session id, or options used to automatically create one.
property createData
createData: ( data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<string>;
Creates a new record with the given data and returns the session id.
property deleteData
deleteData: (id: string) => Promise<void>;
Deletes data for a given session id from the data store.
property readData
readData: (id: string) => Promise<FlashSessionData<Data, FlashData> | null>;
Returns data for a given session id, or
null
if there isn't any.
property updateData
updateData: ( id: string, data: FlashSessionData<Data, FlashData>, expires?: Date) => Promise<void>;
Updates data for the given session id.
interface SessionStorage
interface SessionStorage<Data = SessionData, FlashData = Data> {}
SessionStorage stores session data between HTTP requests and knows how to parse and create cookies.
A SessionStorage creates Session objects using a
Cookie
header as input. Then, later it generates theSet-Cookie
header to be used in the response.
property commitSession
commitSession: ( session: Session<Data, FlashData>, options?: SerializeOptions) => Promise<string>;
Stores all data in the Session and returns the Set-Cookie header to be used in the HTTP response.
property destroySession
destroySession: ( session: Session<Data, FlashData>, options?: SerializeOptions) => Promise<string>;
Deletes all data associated with the Session and returns the Set-Cookie header to be used in the HTTP response.
property getSession
getSession: ( cookieHeader?: string | null, options?: ParseOptions) => Promise<Session<Data, FlashData>>;
Parses a Cookie header from a HTTP request and returns the associated Session. If there is no session associated with the cookie, this will return a new Session with no data.
interface ShouldRevalidateFunction
interface ShouldRevalidateFunction {}
Route shouldRevalidate function signature. This runs after any submission (navigation or fetcher), so we flatten the navigation/fetcher submission onto the arguments. It shouldn't matter whether it came from a navigation or a fetcher, what really matters is the URLs and the formData since loaders have to re-run based on the data models that were potentially mutated.
call signature
(args: ShouldRevalidateFunctionArgs): boolean;
interface ShouldRevalidateFunctionArgs
interface ShouldRevalidateFunctionArgs {}
Arguments passed to shouldRevalidate function
property actionResult
actionResult?: any;
property actionStatus
actionStatus?: number;
property currentParams
currentParams: AgnosticDataRouteMatch['params'];
property currentUrl
currentUrl: URL;
property defaultShouldRevalidate
defaultShouldRevalidate: boolean;
property formAction
formAction?: Submission['formAction'];
property formData
formData?: Submission['formData'];
property formEncType
formEncType?: Submission['formEncType'];
property formMethod
formMethod?: Submission['formMethod'];
property json
json?: Submission['json'];
property nextParams
nextParams: AgnosticDataRouteMatch['params'];
property nextUrl
nextUrl: URL;
property text
text?: Submission['text'];
interface StaticHandler
interface StaticHandler {}
A StaticHandler instance manages a singular SSR navigation/fetch event
property dataRoutes
dataRoutes: AgnosticDataRouteObject[];
method query
query: ( request: Request, opts?: { requestContext?: unknown; skipLoaderErrorBubbling?: boolean; dataStrategy?: DataStrategyFunction; }) => Promise<StaticHandlerContext | Response>;
method queryRoute
queryRoute: ( request: Request, opts?: { routeId?: string; requestContext?: unknown; dataStrategy?: DataStrategyFunction; }) => Promise<any>;
interface StaticHandlerContext
interface StaticHandlerContext {}
State returned from a server-side query() call
property actionData
actionData: RouterState['actionData'];
property actionHeaders
actionHeaders: Record<string, Headers>;
property basename
basename: Router['basename'];
property errors
errors: RouterState['errors'];
property loaderData
loaderData: RouterState['loaderData'];
property loaderHeaders
loaderHeaders: Record<string, Headers>;
property location
location: RouterState['location'];
property matches
matches: RouterState['matches'];
property statusCode
statusCode: number;
interface StaticRouterProps
interface StaticRouterProps {}
interface StaticRouterProviderProps
interface StaticRouterProviderProps {}
interface SubmitFunction
interface SubmitFunction {}
Submits a HTML
<form>
to the server without reloading the page.
call signature
( /** Can be multiple types of elements and objects
**`HTMLFormElement`**
```tsx <Form onSubmit={(event) => { submit(event.currentTarget); }} /> ```
**`FormData`**
```tsx const formData = new FormData(); formData.append("myKey", "myValue"); submit(formData, { method: "post" }); ```
**Plain object that will be serialized as `FormData`**
```tsx submit({ myKey: "myValue" }, { method: "post" }); ```
**Plain object that will be serialized as JSON**
```tsx submit( { myKey: "myValue" }, { method: "post", encType: "application/json" } ); ``` */ target: SubmitTarget, /** * Options that override the `<form>`'s own attributes. Required when * submitting arbitrary data without a backing `<form>`. */ options?: SubmitOptions): Promise<void>;
interface SubmitOptions
interface SubmitOptions extends FetcherSubmitOptions {}
Submit options available to navigations
property fetcherKey
fetcherKey?: string;
Indicate a specific fetcherKey to use when using navigate=false
property navigate
navigate?: boolean;
navigate=false will use a fetcher instead of a navigation
property replace
replace?: boolean;
Set
true
to replace the current entry in the browser's history stack instead of creating a new one (i.e. stay on "the same page"). Defaults tofalse
.
property state
state?: any;
State object to add to the history stack entry for this navigation
property viewTransition
viewTransition?: boolean;
Enable view transitions on this submission navigation
interface UIMatch
interface UIMatch<Data = unknown, Handle = unknown> {}
interface UNSAFE_AssetsManifest
interface AssetsManifest {}
interface UNSAFE_RouteModules
interface RouteModules {}
index signature
[routeId: string]: RouteModule | undefined;
Enums
enum NavigationType
enum NavigationType { Pop = 'POP', Push = 'PUSH', Replace = 'REPLACE',}
Actions represent the type of change to a location value.
member Pop
Pop = 'POP'
A POP indicates a change to an arbitrary index in the history stack, such as a back or forward navigation. It does not describe the direction of the navigation, only that the current index changed.
Note: This is the default action for newly created history objects.
member Push
Push = 'PUSH'
A PUSH indicates a new entry being added to the history stack, such as when a link is clicked and a new page loads. When this happens, all subsequent entries in the stack are lost.
member Replace
Replace = 'REPLACE'
A REPLACE indicates the entry at the current index in the history stack being replaced by a new one.
enum UNSAFE_ServerMode
enum UNSAFE_ServerMode { Development = 'development', Production = 'production', Test = 'test',}
The mode to use when running the server.
member Development
Development = 'development'
member Production
Production = 'production'
member Test
Test = 'test'
Type Aliases
type Blocker
type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;
type BlockerFunction
type BlockerFunction = (args: { currentLocation: Location; nextLocation: Location; historyAction: Action;}) => boolean;
type ClientActionFunction
type ClientActionFunction = ( args: ClientActionFunctionArgs) => ReturnType<ActionFunction>;
A function that handles data mutations for a route on the client
type ClientActionFunctionArgs
type ClientActionFunctionArgs = ActionFunctionArgs<undefined> & { serverAction: <T = unknown>() => Promise<SerializeFrom<T>>;};
Arguments passed to a route
clientAction
function
type ClientLoaderFunction
type ClientLoaderFunction = (( args: ClientLoaderFunctionArgs) => ReturnType<LoaderFunction>) & { hydrate?: boolean;};
A function that loads data for a route on the client
type ClientLoaderFunctionArgs
type ClientLoaderFunctionArgs = LoaderFunctionArgs<undefined> & { serverLoader: <T = unknown>() => Promise<SerializeFrom<T>>;};
Arguments passed to a route
clientLoader
function
type CookieOptions
type CookieOptions = ParseOptions & SerializeOptions & CookieSignatureOptions;
type CreateRequestHandlerFunction
type CreateRequestHandlerFunction = ( build: ServerBuild | (() => ServerBuild | Promise<ServerBuild>), mode?: string) => RequestHandler;
type DataRouteObject
type DataRouteObject = RouteObject & { children?: DataRouteObject[]; id: string;};
type ErrorResponse
type ErrorResponse = { status: number; statusText: string; data: any;};
type Fetcher
type Fetcher<TData = any> = FetcherStates<TData>[keyof FetcherStates<TData>];
type FetcherWithComponents
type FetcherWithComponents<TData> = Fetcher<TData> & { /** Just like {@link Form} except it doesn't cause a navigation. ```tsx function SomeComponent() { const fetcher = useFetcher() return ( <fetcher.Form method="post" action="/some/route"> <input type="text" /> </fetcher.Form> ) } ``` */ Form: React.ForwardRefExoticComponent< FetcherFormProps & React.RefAttributes<HTMLFormElement> >; /** Submits form data to a route. While multiple nested routes can match a URL, only the leaf route will be called. The `formData` can be multiple types: - [`FormData`][form_data] - A `FormData` instance. - [`HTMLFormElement`][html_form_element] - A [`<form>`][form_element] DOM element. - `Object` - An object of key/value pairs that will be converted to a `FormData` instance by default. You can pass a more complex object and serialize it as JSON by specifying `encType: "application/json"`. See [`useSubmit`][use-submit] for more details. If the method is `GET`, then the route [`loader`][loader] is being called and with the `formData` serialized to the url as [`URLSearchParams`][url_search_params]. If `DELETE`, `PATCH`, `POST`, or `PUT`, then the route [`action`][action] is being called with `formData` as the body. ```tsx // Submit a FormData instance (GET request) const formData = new FormData(); fetcher.submit(formData); // Submit the HTML form element fetcher.submit(event.currentTarget.form, { method: "POST", }); // Submit key/value JSON as a FormData instance fetcher.submit( { serialized: "values" }, { method: "POST" } ); // Submit raw JSON fetcher.submit( { deeply: { nested: { json: "values", }, }, }, { method: "POST", encType: "application/json", } ); ``` */ submit: FetcherSubmitFunction; /** Loads data from a route. Useful for loading data imperatively inside of user events outside of a normal button or form, like a combobox or search input. ```tsx let fetcher = useFetcher() <input onChange={e => { fetcher.load(`/search?q=${e.target.value}`) }} /> ``` */ load: ( href: string, opts?: { /** * Wraps the initial state update for this `fetcher.load` in a * `ReactDOM.flushSync` call instead of the default `React.startTransition`. * This allows you to perform synchronous DOM actions immediately after the * update is flushed to the DOM. */ flushSync?: boolean; } ) => Promise<void>;};
The return value of
useFetcher
that keeps track of the state of a fetcher.let fetcher = useFetcher();
type FlashSessionData
type FlashSessionData<Data, FlashData> = Partial< Data & { [Key in keyof FlashData as FlashDataKey<Key & string>]: FlashData[Key]; }>;
type FormEncType
type FormEncType = | 'application/x-www-form-urlencoded' | 'multipart/form-data' | 'application/json' | 'text/plain';
type FormMethod
type FormMethod = UpperCaseFormMethod;
Active navigation/fetcher form methods are exposed in uppercase on the RouterState. This is to align with the normalization done via fetch().
type HeadersArgs
type HeadersArgs = { loaderHeaders: Headers; parentHeaders: Headers; actionHeaders: Headers; errorHeaders: Headers | undefined;};
type HTMLFormMethod
type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;
Users can specify either lowercase or uppercase form methods on
<Form>
, useSubmit(),<fetcher.Form>
, etc.
type HtmlLinkDescriptor
type HtmlLinkDescriptor = | (HtmlLinkProps & Pick<Required<HtmlLinkProps>, 'href'>) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, 'imageSizes'>) | (HtmlLinkPreloadImage & Pick<Required<HtmlLinkPreloadImage>, 'href'> & { imageSizes?: never; });
Represents a
<link>
element.WHATWG Specification: https://html.spec.whatwg.org/multipage/semantics.html#the-link-element
type HydrationState
type HydrationState = Partial< Pick<RouterState, 'loaderData' | 'actionData' | 'errors'>>;
Data that can be passed into hydrate a Router from SSR
type InitialEntry
type InitialEntry = string | Partial<Location>;
A user-supplied object that describes a location. Used when providing entries to
createMemoryHistory
via itsinitialEntries
option.
type IsCookieFunction
type IsCookieFunction = (object: any) => object is Cookie;
type IsSessionFunction
type IsSessionFunction = (object: any) => object is Session;
type LinkDescriptor
type LinkDescriptor = HtmlLinkDescriptor | PageLinkDescriptor;
type LoaderFunction
type LoaderFunction<Context = any> = { ( args: LoaderFunctionArgs<Context>, handlerCtx?: unknown ): DataFunctionReturnValue;} & { hydrate?: boolean;};
Route loader function signature
type MetaDescriptor
type MetaDescriptor = | { charSet: 'utf-8'; } | { title: string; } | { name: string; content: string; } | { property: string; content: string; } | { httpEquiv: string; content: string; } | { 'script:ld+json': LdJsonObject; } | { tagName: 'meta' | 'link'; [name: string]: string; } | { [name: string]: unknown; };
type Navigation
type Navigation = NavigationStates[keyof NavigationStates];
type NavigationStates
type NavigationStates = { Idle: { state: 'idle'; location: undefined; formMethod: undefined; formAction: undefined; formEncType: undefined; formData: undefined; json: undefined; text: undefined; }; Loading: { state: 'loading'; location: Location; formMethod: Submission['formMethod'] | undefined; formAction: Submission['formAction'] | undefined; formEncType: Submission['formEncType'] | undefined; formData: Submission['formData'] | undefined; json: Submission['json'] | undefined; text: Submission['text'] | undefined; }; Submitting: { state: 'submitting'; location: Location; formMethod: Submission['formMethod']; formAction: Submission['formAction']; formEncType: Submission['formEncType']; formData: Submission['formData']; json: Submission['json']; text: Submission['text']; };};
Potential states for state.navigation
type NavLinkRenderProps
type NavLinkRenderProps = { /** * Indicates if the link's URL matches the current location. */ isActive: boolean; /** * Indicates if the pending location matches the link's URL. */ isPending: boolean; /** * Indicates if a view transition to the link's URL is in progress. See {@link useViewTransitionState} */ isTransitioning: boolean;};
The object passed to NavLink
children
,className
, andstyle
prop callbacks to render and style the link based on its state.``` // className <NavLink to="/messages" className={({ isActive, isPending }) => isPending ? "pending" : isActive ? "active" : "" } > Messages
// style <NavLink to="/messages" style={({ isActive, isPending }) => { return { fontWeight: isActive ? "bold" : "", color: isPending ? "red" : "black", } )} />
// children {({ isActive, isPending }) => ( <span className={isActive ? "active" : ""}>Tasks )} ```
type ParamKeyValuePair
type ParamKeyValuePair = [string, string];
type ParamParseKey
type ParamParseKey<Segment extends string> = [PathParam<Segment>] extends [never] ? string : PathParam<Segment>;
type Params
type Params<Key extends string = string> = { readonly [key in Key]: string | undefined;};
The parameters that were parsed from the URL path.
type PatchRoutesOnNavigationFunction
type PatchRoutesOnNavigationFunction = AgnosticPatchRoutesOnNavigationFunction< RouteObject, RouteMatch>;
type PatchRoutesOnNavigationFunctionArgs
type PatchRoutesOnNavigationFunctionArgs = AgnosticPatchRoutesOnNavigationFunctionArgs<RouteObject, RouteMatch>;
type PathParam
type PathParam<Path extends string> = Path extends '*' | '/*' ? '*' : Path extends `${infer Rest}/*` ? '*' | _PathParam<Rest> : _PathParam<Path>;
type RedirectFunction
type RedirectFunction = (url: string, init?: number | ResponseInit) => Response;
type RelativeRoutingType
type RelativeRoutingType = 'route' | 'path';
- "route": relative to the route hierarchy so
..
means remove all segments of the current route even if it has many. For example, aroute("posts/:id")
would have both:id
andposts
removed from the url. - "path": relative to the pathname so..
means remove one segment of the pathname. For example, aroute("posts/:id")
would have only:id
removed from the url.
type RequestHandler
type RequestHandler = ( request: Request, loadContext?: AppLoadContext$1) => Promise<Response>;
type RevalidationState
type RevalidationState = 'idle' | 'loading';
type RouteObject
type RouteObject = IndexRouteObject | NonIndexRouteObject;
type RouteProps
type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;
type RouterFetchOptions
type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;
Options to pass to fetch()
type RouterNavigateOptions
type RouterNavigateOptions = LinkNavigateOptions | SubmissionNavigateOptions;
Options to pass to navigate() for a navigation
type ScriptsProps
type ScriptsProps = Omit< React.HTMLProps<HTMLScriptElement>, | 'children' | 'async' | 'defer' | 'src' | 'type' | 'noModule' | 'dangerouslySetInnerHTML' | 'suppressHydrationWarning'>;
A couple common attributes:
-
<Scripts crossOrigin>
for hosting your static assets on a different server than your app. -<Scripts nonce>
to support a [content security policy for scripts](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src) with [nonce-sources](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/Sources#sources) for your<script>
tags.You cannot pass through attributes such as
async
,defer
,src
,type
,noModule
because they are managed by React Router internally.Types
type ScrollRestorationProps
type ScrollRestorationProps = ScriptsProps & { /** Defines the key used to restore scroll positions. ```tsx <ScrollRestoration getKey={(location, matches) => { // default behavior return location.key }} /> ``` */ getKey?: GetScrollRestorationKeyFunction; storageKey?: string;};
type SetURLSearchParams
type SetURLSearchParams = ( nextInit?: | URLSearchParamsInit | ((prev: URLSearchParams) => URLSearchParamsInit), navigateOpts?: NavigateOptions) => void;
Sets new search params and causes a navigation when called.
```tsx <button onClick={() => { const params = new URLSearchParams(); params.set("someKey", "someValue"); setSearchParams(params, { preventScrollReset: true, }); }} /> ```
It also supports a function for setting new search params.
```tsx <button onClick={() => { setSearchParams((prev) => { prev.set("someKey", "someValue"); return prev; }); }} /> ```
type SubmitTarget
type SubmitTarget = | HTMLFormElement | HTMLButtonElement | HTMLInputElement | FormData | URLSearchParams | JsonValue | null;
type To
type To = string | Partial<Path>;
Describes a location that is the destination of some navigation used in Link, useNavigate, etc.
type URLSearchParamsInit
type URLSearchParamsInit = | string | ParamKeyValuePair[] | Record<string, string | string[]> | URLSearchParams;
Namespaces
namespace ScrollRestoration
namespace ScrollRestoration {}
variable displayName
var displayName: string;
namespace unstable_HistoryRouter
namespace unstable_HistoryRouter {}
variable displayName
var displayName: string;
Package Files (4)
Dependencies (4)
Dev Dependencies (7)
Peer Dependencies (2)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/react-router
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/react-router)
- HTML<a href="https://www.jsdocs.io/package/react-router"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 10654 ms. - Missing or incorrect documentation? Open an issue for this package.