W↓
All docs
🔑
Sign Up/Sign In
reactrouter.com/api/
Public Link
Apr 16, 2025, 7:57:54 AM - complete - 59 kB
Apr 16, 2025, 7:57:54 AM - complete - 59 kB
Apr 8, 2025, 12:37:41 PM - complete - 62.6 kB
Starting URLs:
https://reactrouter.com/api/components/Await
CSS Selector:
.markdown
Crawl Prefixes:
https://reactrouter.com/api/
## Page: https://reactrouter.com/api/components/Await # Await * Framework * Data * Declarative ## Summary Reference Documentation ↗ Used to render promise values with automatic error handling. import { Await, useLoaderData } from "react-router"; export function loader() { // not awaited const 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 />}> <Await resolve={reviews} errorElement={ <div>Could not load reviews 😬</div> } children={(resolvedReviews) => ( <Reviews items={resolvedReviews} /> )} /> </React.Suspense> </div> ); } `<Await>` expects to be rendered inside of a `<React.Suspense>` ## Props ### children * * * When using a function, the resolved value is provided as the parameter. <Await resolve={reviewsPromise}> {(resolvedReviews) => <Reviews items={resolvedReviews} />} </Await> When using React elements, useAsyncValue will provide the resolved value: <Await resolve={reviewsPromise}> <Reviews /> </Await>; function Reviews() { const resolvedReviews = useAsyncValue(); return <div>...</div>; } ### errorElement * * * The error element renders instead of the children when the promise rejects. <Await errorElement={<div>Oops</div>} resolve={reviewsPromise} > <Reviews /> </Await> To provide a more contextual error, you can use the useAsyncError in a child component <Await errorElement={<ReviewsError />} resolve={reviewsPromise} > <Reviews /> </Await>; function ReviewsError() { const error = useAsyncError(); return <div>Error loading reviews: {error.message}</div>; } 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. ### resolve * * * Takes a promise returned from a LoaderFunction value to be resolved and rendered. 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 ( <div> <h1>{book.title}</h1> <p>{book.description}</p> <React.Suspense fallback={<ReviewsSkeleton />}> <Await // and is the promise we pass to Await resolve={reviews} > <Reviews /> </Await> </React.Suspense> </div> ); } --- ## Page: https://reactrouter.com/api/components/Form # Form * Framework * Data * Declarative ## Summary Reference Documentation ↗ A progressively enhanced HTML `<form>` that submits data to actions via `fetch`, activating pending states in `useNavigation` 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> ); } ## Props ### action * * * The URL to submit the form data to. If `undefined`, this defaults to the closest route in context. ### discover * * * Determines application manifest discovery behavior. ### encType * * * The encoding type to use for the form submission. ### fetcherKey * * * 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. ### method * * * The HTTP verb to use when the form is submitted. Supports "get", "post", "put", "delete", and "patch". Native `<form>` only supports `get` and `post`, avoid the other verbs if you'd like to support progressive enhancement ### navigate * * * Skips the navigation and uses a useFetcher internally when `false`. This is essentially a shorthand for `useFetcher()` + `<fetcher.Form>` where you don't care about the resulting data in this component. ### onSubmit * * * A function to call when the form is submitted. If you call `event.preventDefault()` then this form will not do anything. ### preventScrollReset * * * Prevent the scroll position from resetting to the top of the viewport on completion of the navigation when using the component ### relative * * * Determines whether the form action is relative to the route hierarchy or the pathname. Use this if you want to opt out of navigating the route hierarchy and want to instead route based on /-delimited URL segments ### reloadDocument * * * Forces a full document navigation instead of client side routing + data fetch. ### replace * * * 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. ### state * * * State object to add to the history stack entry for this navigation ### viewTransition * * * Enables a View Transition for this navigation. To apply specific styles during the transition see useViewTransitionState. --- ## Page: https://reactrouter.com/api/components/Link # Link * Framework * Data * Declarative ## Summary Reference Documentation ↗ A progressively enhanced `<a href>` wrapper to enable navigation with client-side routing. import { Link } from "react-router"; <Link to="/dashboard">Dashboard</Link>; <Link to={{ pathname: "/some/path", search: "?query=string", hash: "#hash", }} />; ## Props ### discover * * * Defines the link discovery behavior <Link discover="render" /> * **render** - default, discover the route when the link renders * **none** - don't eagerly discover, only discover if the link is clicked ### prefetch * * * Defines the data and module prefetching behavior for the link. <Link prefetch="intent" /> * **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. <a href="..." /> <a href="..." /> <link rel="prefetch" /> // might conditionally render Because of this, if you are using `nav :last-child` you will need to use `nav :last-of-type` so the styles don't conditionally fall off your last link (and any other similar selectors). ### preventScrollReset * * * 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. <Link to="?tab=one" preventScrollReset /> ### relative * * * Defines the relative path behavior for the link. <Link to=".." /> // default: "route" <Link relative="route" /> <Link relative="path" /> 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" ### reloadDocument * * * 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>`). <Link to="/logout" reloadDocument /> ### replace * * * Replaces the current entry in the history stack instead of pushing a new one onto it. <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 ### state * * * Adds persistent client side routing state to the next location. <Link to="/somewhere/else" state={{ some: "value" }} /> The location state is accessed from the `location`. 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` ### to * * * Can be a string or a partial Path: <Link to="/some/path" /> <Link to={{ pathname: "/some/path", search: "?query=string", hash: "#hash", }} /> ### viewTransition * * * Enables a View Transition for this navigation. <Link to={to} viewTransition> Click me </Link> To apply specific styles for the transition, see useViewTransitionState --- ## Page: https://reactrouter.com/api/components/Links # Links * Framework * Data * Declarative ## Summary Reference Documentation ↗ Renders all of the `<link>` tags created by route module `links` export. You should render it inside the `<head>` of your document. import { Links } from "react-router"; export default function Root() { return ( <html> <head> <Links /> </head> <body></body> </html> ); } ## Props None --- ## Page: https://reactrouter.com/api/components/Meta # Meta * Framework * Data * Declarative ## Summary Reference Documentation ↗ Renders all the `<meta>` tags created by route module `meta` export. You should render it inside the `<head>` of your HTML. import { Meta } from "react-router"; export default function Root() { return ( <html> <head> <Meta /> </head> </html> ); } ## Props None --- ## Page: https://reactrouter.com/api/components/NavLink # NavLink * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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` on MDN. import { NavLink } from "react-router"; <NavLink to="/message" />; States are available through the className, style, and children render props. See NavLinkRenderProps. <NavLink to="/messages" className={({ isActive, isPending }) => isPending ? "pending" : isActive ? "active" : "" } > Messages </NavLink> ## Props ### caseSensitive * * * 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 | ### children * * * Can be regular React children or a function that receives an object with the active and pending states of the link. <NavLink to="/tasks"> {({ isActive }) => ( <span className={isActive ? "active" : ""}>Tasks</span> )} </NavLink> ### className * * * Classes are automatically applied to NavLink that correspond to the state. a.active { color: red; } a.pending { color: blue; } a.transitioning { view-transition-name: my-transition; } Note that `pending` is only available with Framework and Data modes. ### discover * * * Defines the link discovery behavior <Link discover="render" /> * **render** - default, discover the route when the link renders * **none** - don't eagerly discover, only discover if the link is clicked ### end * * * Changes the matching logic for the `active` and `pending` 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 the `end` prop and only matches when you're at the root route. ### prefetch * * * Defines the data and module prefetching behavior for the link. <Link prefetch="intent" /> * **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. <a href="..." /> <a href="..." /> <link rel="prefetch" /> // might conditionally render Because of this, if you are using `nav :last-child` you will need to use `nav :last-of-type` so the styles don't conditionally fall off your last link (and any other similar selectors). ### preventScrollReset * * * 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. <Link to="?tab=one" preventScrollReset /> ### relative * * * Defines the relative path behavior for the link. <Link to=".." /> // default: "route" <Link relative="route" /> <Link relative="path" /> 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" ### reloadDocument * * * 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>`). <Link to="/logout" reloadDocument /> ### replace * * * Replaces the current entry in the history stack instead of pushing a new one onto it. <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 ### state * * * Adds persistent client side routing state to the next location. <Link to="/somewhere/else" state={{ some: "value" }} /> The location state is accessed from the `location`. 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` ### style * * * Regular React style object or a function that receives an object with the active and pending states of the link. <NavLink to="/tasks" style={{ color: "red" }} /> <NavLink to="/tasks" style={({ isActive, isPending }) => ({ color: isActive ? "red" : isPending ? "blue" : "black" })} /> Note that `pending` is only available with Framework and Data modes. ### to * * * Can be a string or a partial Path: <Link to="/some/path" /> <Link to={{ pathname: "/some/path", search: "?query=string", hash: "#hash", }} /> ### viewTransition * * * Enables a View Transition for this navigation. <Link to={to} viewTransition> Click me </Link> To apply specific styles for the transition, see useViewTransitionState --- ## Page: https://reactrouter.com/api/components/Navigate # Navigate * Framework * Data * Declarative ## Summary Reference Documentation ↗ A component-based version of useNavigate to use in a `React.Component Class` where hooks are not able to be used. It's recommended to avoid using this component in favor of useNavigate <Navigate to="/tasks" /> ## Props ### relative * * * _No documentation_ ### replace * * * _No documentation_ ### state * * * _No documentation_ ### to * * * _No documentation_ --- ## Page: https://reactrouter.com/api/components/Outlet # Outlet * Framework * Data * Declarative ## Summary Reference Documentation ↗ Renders the matching child route of a parent route or nothing if no child route matches. import { Outlet } from "react-router"; export default function SomeParent() { return ( <div> <h1>Parent Content</h1> <Outlet /> </div> ); } ## Props ### context * * * Provides a context value to the element tree below the outlet. Use when the parent route needs to provide values to child routes. <Outlet context={myContextValue} /> Access the context with useOutletContext. --- ## Page: https://reactrouter.com/api/components/PrefetchPageLinks # PrefetchPageLinks * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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. import { PrefetchPageLinks } from "react-router"; <PrefetchPageLinks page="/absolute/path" />; 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. ## Props ### crossOrigin * * * How the element handles crossorigin requests ### disabled * * * Whether the link is disabled ### hrefLang * * * Language of the linked resource ### integrity * * * Integrity metadata used in Subresource Integrity checks ### media * * * Applicable media: "screen", "print", "(max-width: 764px)" ### page * * * The absolute path of the page to prefetch. ### referrerPolicy * * * Referrer policy for fetches initiated by the element --- ## Page: https://reactrouter.com/api/components/Route # Route * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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. ## Props ### caseSensitive * * * Whether the path should be matched in a case-sensitive manner. ### children * * * _No documentation_ ### Component * * * _No documentation_ ### element * * * _No documentation_ ### path * * * The path to match against the current location. --- ## Page: https://reactrouter.com/api/components/Routes # Routes * Framework * Data * Declarative ## Summary Reference Documentation ↗ Renders a branch of Route 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. import { Routes, Route } from "react-router" <Routes> <Route index element={<StepOne />} /> <Route path="step-2" element={<StepTwo />} /> <Route path="step-3" element={<StepThree />}> </Routes> ## Props ### children * * * Nested Route elements ### location * * * The location to match against. Defaults to the current location. --- ## Page: https://reactrouter.com/api/components/Scripts # Scripts * Framework * Data * Declarative ## Summary Reference Documentation ↗ Renders the client runtime of your app. It should be rendered inside the `<body>` of the document. import { Scripts } from "react-router"; export default function Root() { return ( <html> <head /> <body> <Scripts /> </body> </html> ); } 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. ## Props ### ScriptsProps * * * 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 with nonce-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. --- ## Page: https://reactrouter.com/api/components/ScrollRestoration # ScrollRestoration * Framework * Data * Declarative ## Summary Reference Documentation ↗ Emulates the browser's scroll restoration on location changes. Apps should only render one of these, right before the Scripts component. import { ScrollRestoration } from "react-router"; export default function Root() { return ( <html> <body> <ScrollRestoration /> <Scripts /> </body> </html> ); } This component renders an inline `<script>` to prevent scroll flashing. The `nonce` prop will be passed down to the script tag to allow CSP nonce usage. <ScrollRestoration nonce={cspNonce} /> ## Props ### ScriptsProps * * * 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 with nonce-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. --- ## Page: https://reactrouter.com/api/components/ServerRouter # ServerRouter * Framework * Data * Declarative ## Summary Reference Documentation ↗ Rendered at the top of the app in a custom entry.server.tsx. ## Props ### context * * * _No documentation_ ### nonce * * * _No documentation_ ### url * * * _No documentation_ --- ## Page: https://reactrouter.com/api/hooks/unstable_usePrompt # unstable\_usePrompt * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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. 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 ( <Form method="post"> <label> Enter some important data: <input name="data" value={value} onChange={(e) => setValue(e.target.value)} /> </label> <button type="submit">Save</button> </Form> ); } ## Signature unstable_usePrompt(options): void ## Params ### options _No documentation_ --- ## Page: https://reactrouter.com/api/hooks/useActionData # useActionData * Framework * Data * Declarative ## Summary Reference Documentation ↗ Returns the action data from the most recent POST navigation form submission or `undefined` if there hasn't been one. 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 ( <Form method="post"> <input type="text" name="visitorsName" /> {data ? data.message : "Waiting..."} </Form> ); } ## Signature useActionData(): undefined --- ## Page: https://reactrouter.com/api/hooks/useAsyncError # useAsyncError * Framework * Data * Declarative ## Summary Reference Documentation ↗ Returns the rejection value from the closest Await. import { Await, useAsyncError } from "react-router"; function ErrorElement() { const error = useAsyncError(); return ( <p>Uh Oh, something went wrong! {error.message}</p> ); } // somewhere in your app <Await resolve={promiseThatRejects} errorElement={<ErrorElement />} />; ## Signature useAsyncError(): unknown --- ## Page: https://reactrouter.com/api/hooks/useAsyncValue # useAsyncValue * Framework * Data * Declarative ## Summary Reference Documentation ↗ Returns the resolved promise value from the closest Await. function SomeDescendant() { const value = useAsyncValue(); // ... } // somewhere in your app <Await resolve={somePromise}> <SomeDescendant /> </Await>; ## Signature useAsyncValue(): unknown --- ## Page: https://reactrouter.com/api/hooks/useBeforeUnload # useBeforeUnload * Framework * Data * Declarative ## Summary Reference Documentation ↗ Setup a callback to be fired on the window's `beforeunload` event. ## Signature useBeforeUnload(callback, options): void ## Params ### callback * * * _No documentation_ ### options * * * _No documentation_ --- ## Page: https://reactrouter.com/api/hooks/useBlocker # useBlocker * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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. ## Signature useBlocker(shouldBlock): Blocker ## Params ### shouldBlock * * * _No documentation_ --- ## Page: https://reactrouter.com/api/hooks/useFetcher # useFetcher * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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. 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" }) } ## Signature useFetcher(options): FetcherWithComponents ## Params ### options * * * _No documentation_ --- ## Page: https://reactrouter.com/api/hooks/useFetchers # useFetchers * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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. import { useFetchers } from "react-router"; function SomeComponent() { const fetchers = useFetchers(); fetchers[0].formData; // FormData fetchers[0].state; // etc. // ... } ## Signature useFetchers(): undefined --- ## Page: https://reactrouter.com/api/hooks/useFormAction # useFormAction * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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. import { useFormAction } from "react-router"; function SomeComponent() { // closest route URL let action = useFormAction(); // closest route URL + "destroy" let destroyAction = useFormAction("destroy"); } ## Signature useFormAction(action, __namedParameters): string ## Params ### action * * * The action to append to the closest route URL. ### \_\_namedParameters * * * _No documentation_ --- ## Page: https://reactrouter.com/api/hooks/useHref # useHref * Framework * Data * Declarative ## Summary Reference Documentation ↗ Resolves a URL against the current location. import { useHref } from "react-router"; function SomeComponent() { let href = useHref("some/where"); // "/resolved/some/where" } ## Signature useHref(to, __namedParameters): string ## Params ### to * * * _No documentation_ ### \_\_namedParameters * * * _No documentation_ --- ## Page: https://reactrouter.com/api/hooks/useInRouterContext # useInRouterContext * Framework * Data * Declarative ## Summary Reference Documentation ↗ Returns true if this component is a descendant of a Router, useful to ensure a component is used within a Router. ## Signature useInRouterContext(): boolean --- ## Page: https://reactrouter.com/api/hooks/useLinkClickHandler # useLinkClickHandler * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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>`. ## Signature useLinkClickHandler(to, __namedParameters): undefined ## Params ### to * * * _No documentation_ ### \_\_namedParameters * * * _No documentation_ --- ## Page: https://reactrouter.com/api/hooks/useLoaderData # useLoaderData * Framework * Data * Declarative ## Summary Reference Documentation ↗ Returns the data from the closest route LoaderFunction or ClientLoaderFunction. import { useLoaderData } from "react-router"; export async function loader() { return await fakeDb.invoices.findAll(); } export default function Invoices() { let invoices = useLoaderData<typeof loader>(); // ... } ## Signature useLoaderData(): SerializeFrom --- ## Page: https://reactrouter.com/api/hooks/useLocation # useLocation * Framework * Data * Declarative ## Summary Reference Documentation ↗ Returns the current Location. This can be useful if you'd like to perform some side effect whenever it changes. import * as React from 'react' import { useLocation } from 'react-router' function SomeComponent() { let location = useLocation() React.useEffect(() => { // Google Analytics ga('send', 'pageview') }, [location]); return ( // ... ); } ## Signature useLocation(): Location --- ## Page: https://reactrouter.com/api/hooks/useMatch # useMatch * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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>`. ## Signature useMatch(pattern): undefined ## Params ### pattern * * * _No documentation_ --- ## Page: https://reactrouter.com/api/hooks/useMatches # useMatches * Framework * Data * Declarative ## Summary Reference Documentation ↗ Returns the active route matches, useful for accessing loaderData for parent/child routes or the route "handle" property ## Signature useMatches(): undefined --- ## Page: https://reactrouter.com/api/hooks/useNavigate # useNavigate * Framework * Data * Declarative ## Summary Reference Documentation ↗ Returns a function that lets you navigate programmatically in the browser in response to user interactions or effects. import { useNavigate } from "react-router"; function SomeComponent() { let navigate = useNavigate(); return ( <button onClick={() => { navigate(-1); }} /> ); } It's often better to use redirect in ActionFunction and LoaderFunction than this hook. ## Signature useNavigate(): NavigateFunction --- ## Page: https://reactrouter.com/api/hooks/useNavigation # useNavigation * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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. import { useNavigation } from "react-router"; function SomeComponent() { let navigation = useNavigation(); navigation.state; navigation.formData; // etc. } ## Signature useNavigation(): Navigation --- ## Page: https://reactrouter.com/api/hooks/useNavigationType # useNavigationType * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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. ## Signature useNavigationType(): NavigationType --- ## Page: https://reactrouter.com/api/hooks/useOutlet # useOutlet * Framework * Data * Declarative ## Summary Reference Documentation ↗ Returns the element for the child route at this level of the route hierarchy. Used internally by `<Outlet>` to render child routes. ## Signature useOutlet(context): undefined ## Params ### context * * * _No documentation_ --- ## Page: https://reactrouter.com/api/hooks/useOutletContext # useOutletContext * Framework * Data * Declarative ## Summary Reference Documentation ↗ Returns the parent route `<Outlet context>`. ## Signature useOutletContext(): Context --- ## Page: https://reactrouter.com/api/hooks/useParams # useParams * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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. import { useParams } from "react-router" function SomeComponent() { let params = useParams() params.postId } Assuming a route pattern like `/posts/:postId` is matched by `/posts/123` then `params.postId` will be `"123"`. ## Signature useParams(): Readonly --- ## Page: https://reactrouter.com/api/hooks/useResolvedPath # useResolvedPath * Framework * Data * Declarative ## Summary Reference Documentation ↗ Resolves the pathname of the given `to` value against the current location. Similar to useHref, but returns a Path instead of a string. 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; // "" } ## Signature useResolvedPath(to, __namedParameters): Path ## Params ### to * * * _No documentation_ ### \_\_namedParameters * * * _No documentation_ --- ## Page: https://reactrouter.com/api/hooks/useRevalidator # useRevalidator * Framework * Data * Declarative ## Summary Reference Documentation ↗ Revalidate the data on the page for reasons outside of normal data mutations like window focus or polling on an interval. import { useRevalidator } from "react-router"; function WindowFocusRevalidator() { const revalidator = useRevalidator(); useFakeWindowFocus(() => { revalidator.revalidate(); }); return ( <div hidden={revalidator.state === "idle"}> Revalidating... </div> ); } 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. ## Signature useRevalidator(): undefined --- ## Page: https://reactrouter.com/api/hooks/useRouteError # useRouteError * Framework * Data * Declarative ## Summary Reference Documentation ↗ Accesses the error thrown during an ActionFunction, LoaderFunction, or component render to be used in a route module Error Boundary. export function ErrorBoundary() { const error = useRouteError(); return <div>{error.message}</div>; } ## Signature useRouteError(): unknown --- ## Page: https://reactrouter.com/api/hooks/useRouteLoaderData # useRouteLoaderData * Framework * Data * Declarative ## Summary Reference Documentation ↗ Returns the loader data for a given route by route ID. 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: route("/", "containers/app.tsx", { id: "app" }}) ## Signature useRouteLoaderData(routeId): undefined ## Params ### routeId * * * _No documentation_ --- ## Page: https://reactrouter.com/api/hooks/useRoutes # useRoutes * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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, or `null` if nothing matched. import * as React from "react"; import { useRoutes } from "react-router"; function App() { let element = useRoutes([ { path: "/", element: <Dashboard />, children: [ { path: "messages", element: <DashboardMessages />, }, { path: "tasks", element: <DashboardTasks /> }, ], }, { path: "team", element: <AboutPage /> }, ]); return element; } ## Signature useRoutes(routes, locationArg): undefined ## Params ### routes * * * _No documentation_ ### locationArg * * * _No documentation_ --- ## Page: https://reactrouter.com/api/hooks/useSearchParams # useSearchParams * Framework * Data * Declarative ## Summary Reference Documentation ↗ Returns a tuple of the current URL's URLSearchParams and a function to update them. Setting the search params causes a navigation. import { useSearchParams } from "react-router"; export function SomeComponent() { const [searchParams, setSearchParams] = useSearchParams(); // ... } ## Signature useSearchParams(defaultInit): undefined ## Params ### defaultInit * * * _No documentation_ --- ## Page: https://reactrouter.com/api/hooks/useSubmit # useSubmit * Framework * Data * Declarative ## Summary Reference Documentation ↗ The imperative version of Form that lets you submit a form from code instead of a user interaction. import { useSubmit } from "react-router"; function SomeComponent() { const submit = useSubmit(); return ( <Form onChange={(event) => { submit(event.currentTarget); }} /> ); } ## Signature useSubmit(): SubmitFunction --- ## Page: https://reactrouter.com/api/hooks/useViewTransitionState # useViewTransitionState * Framework * Data * Declarative ## Summary Reference Documentation ↗ This hook returns `true` when there is an active View Transition 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 the `Form`, `submit`, or `navigate` call) ## Signature useViewTransitionState(to, opts): boolean ## Params ### to * * * _No documentation_ ### opts * * * _No documentation_ --- ## Page: https://reactrouter.com/api/data-routers/HydratedRouter # HydratedRouter * Framework * Data * Declarative ## Summary Reference Documentation ↗ Hydrates a server rendered StaticRouterProvider. ## Props None --- ## Page: https://reactrouter.com/api/data-routers/RouterProvider # RouterProvider * Framework * Data * Declarative ## Summary Reference Documentation ↗ Initializes a data router, subscribes to its changes, and renders the matching components. Should typically be at the top of an app's element tree. import { RouterProvider, createBrowserRouter, } from "react-router"; import { createRoot } from "react-dom/client"; let router = createBrowserRouter(); createRoot(document.getElementById("root")).render( <RouterProvider router={router} /> ); ## Props ### flushSync * * * _No documentation_ ### router * * * _No documentation_ --- ## Page: https://reactrouter.com/api/data-routers/StaticRouterProvider # StaticRouterProvider * Framework * Data * Declarative ## Summary Reference Documentation ↗ A Data Router that may not navigate to any other location. This is useful on the server where there is no stateful UI. ## Props ### context * * * _No documentation_ ### hydrate * * * _No documentation_ ### nonce * * * _No documentation_ ### router * * * _No documentation_ --- ## Page: https://reactrouter.com/api/data-routers/createBrowserRouter # createBrowserRouter * Framework * Data * Declarative ## Summary Reference Documentation ↗ ## Signature createBrowserRouter(routes, opts): DataRouter ## Params ### routes * * * _No documentation_ ### opts * * * _No documentation_ --- ## Page: https://reactrouter.com/api/data-routers/createHashRouter # createHashRouter * Framework * Data * Declarative ## Summary Reference Documentation ↗ ## Signature createHashRouter(routes, opts): DataRouter ## Params ### routes * * * _No documentation_ ### opts * * * _No documentation_ --- ## Page: https://reactrouter.com/api/data-routers/createMemoryRouter # createMemoryRouter * Framework * Data * Declarative ## Summary Reference Documentation ↗ ## Signature createMemoryRouter(routes, opts): DataRouter ## Params ### routes * * * _No documentation_ ### opts * * * _No documentation_ --- ## Page: https://reactrouter.com/api/data-routers/createStaticRouter # createStaticRouter * Framework * Data * Declarative ## Summary Reference Documentation ↗ ## Signature createStaticRouter(routes, context, opts): DataRouter ## Params ### routes * * * _No documentation_ ### context * * * _No documentation_ ### opts * * * _No documentation_ --- ## Page: https://reactrouter.com/api/declarative-routers/BrowserRouter # BrowserRouter * Framework * Data * Declarative ## Summary Reference Documentation ↗ A declarative router using the browser history API for client side routing. ## Props ### basename * * * _No documentation_ ### children * * * _No documentation_ ### window * * * _No documentation_ --- ## Page: https://reactrouter.com/api/declarative-routers/HashRouter # HashRouter * Framework * Data * Declarative ## Summary Reference Documentation ↗ A `<Router>` for use in web browsers. Stores the location in the hash portion of the URL. ## Props ### basename * * * _No documentation_ ### children * * * _No documentation_ ### window * * * _No documentation_ --- ## Page: https://reactrouter.com/api/declarative-routers/MemoryRouter # MemoryRouter * Framework * Data * Declarative ## Summary Reference Documentation ↗ A `<Router>` that stores all entries in memory. ## Props ### basename * * * _No documentation_ ### children * * * _No documentation_ ### initialEntries * * * _No documentation_ ### initialIndex * * * _No documentation_ --- ## Page: https://reactrouter.com/api/declarative-routers/Router # Router * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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. ## Props ### basename * * * _No documentation_ ### children * * * _No documentation_ ### location * * * _No documentation_ ### navigationType * * * _No documentation_ ### navigator * * * _No documentation_ ### static * * * _No documentation_ --- ## Page: https://reactrouter.com/api/declarative-routers/StaticRouter # StaticRouter * Framework * Data * Declarative ## Summary Reference Documentation ↗ A `<Router>` that may not navigate to any other location. This is useful on the server where there is no stateful UI. ## Props ### basename * * * _No documentation_ ### children * * * _No documentation_ ### location * * * _No documentation_ --- ## Page: https://reactrouter.com/api/declarative-routers/unstable_HistoryRouter # HistoryRouter * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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. ## Props ### basename * * * _No documentation_ ### children * * * _No documentation_ ### history * * * _No documentation_ --- ## Page: https://reactrouter.com/api/utils/IsCookieFunction # IsCookieFunction * Framework * Data * Declarative ## Summary Reference Documentation ↗ --- ## Page: https://reactrouter.com/api/utils/IsSessionFunction # IsSessionFunction * Framework * Data * Declarative ## Summary Reference Documentation ↗ --- ## Page: https://reactrouter.com/api/utils/createCookie # createCookie * Framework * Data * Declarative ## Summary Reference Documentation ↗ Creates a logical container for managing a browser cookie from the server. --- ## Page: https://reactrouter.com/api/utils/createCookieSessionStorage # createCookieSessionStorage * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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! --- ## Page: https://reactrouter.com/api/utils/createMemorySessionStorage # createMemorySessionStorage * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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. --- ## Page: https://reactrouter.com/api/utils/createPath # createPath * Framework * Data * Declarative ## Summary Reference Documentation ↗ Creates a string URL path from the given pathname, search, and hash components. ## Signature createPath(__namedParameters): string ## Params ### \_\_namedParameters * * * _No documentation_ --- ## Page: https://reactrouter.com/api/utils/createRoutesFromElements # createRoutesFromElements * Framework * Data * Declarative ## Summary Reference Documentation ↗ Create route objects from JSX elements instead of arrays of objects ## Signature createRoutesFromElements(children, parentPath): undefined ## Params ### children * * * _No documentation_ ### parentPath * * * _No documentation_ --- ## Page: https://reactrouter.com/api/utils/createRoutesStub # createRoutesStub * Framework * Data * Declarative ## Summary Reference Documentation ↗ ## Signature createRoutesStub(routes, context): undefined ## Params ### routes * * * _No documentation_ ### context * * * _No documentation_ --- ## Page: https://reactrouter.com/api/utils/createSearchParams # createSearchParams * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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: let searchParams = new URLSearchParams([ ["sort", "name"], ["sort", "price"], ]); you can do: let searchParams = createSearchParams({ sort: ['name', 'price'] }); ## Signature createSearchParams(init): URLSearchParams ## Params ### init * * * _No documentation_ --- ## Page: https://reactrouter.com/api/utils/createStaticHandler # createStaticHandler * Framework * Data * Declarative ## Summary Reference Documentation ↗ ## Signature createStaticHandler(routes, opts): StaticHandler ## Params ### routes * * * _No documentation_ ### opts * * * _No documentation_ --- ## Page: https://reactrouter.com/api/utils/data # data * Framework * Data * Declarative ## Summary Reference Documentation ↗ Create "responses" that contain `status`/`headers` without forcing serialization into an actual `Response` - used by Remix single fetch ## Signature data(data, init): DataWithResponseInit ## Params ### data * * * _No documentation_ ### init * * * _No documentation_ --- ## Page: https://reactrouter.com/api/utils/generatePath # generatePath * Framework * Data * Declarative ## Summary Reference Documentation ↗ Returns a path with params interpolated. ## Signature generatePath(originalPath, params): string ## Params ### originalPath * * * _No documentation_ ### params * * * _No documentation_ --- ## Page: https://reactrouter.com/api/utils/href # href * Framework * Data * Declarative ## Summary Reference Documentation ↗ Returns a resolved URL path for the specified route. const h = href("/:lang?/about", { lang: "en" }) // -> `/en/about` <Link to={href("/products/:id", { id: "abc123" })} /> --- ## Page: https://reactrouter.com/api/utils/isCookie # isCookie * Framework * Data * Declarative ## Summary Reference Documentation ↗ Returns true if an object is a Remix cookie container. --- ## Page: https://reactrouter.com/api/utils/isRouteErrorResponse # isRouteErrorResponse * Framework * Data * Declarative ## Summary Reference Documentation ↗ Check if the given error is an ErrorResponse generated from a 4xx/5xx Response thrown from an action/loader ## Signature isRouteErrorResponse(error): error ## Params ### error * * * _No documentation_ --- ## Page: https://reactrouter.com/api/utils/isSession # isSession * Framework * Data * Declarative ## Summary Reference Documentation ↗ Returns true if an object is a Remix session. --- ## Page: https://reactrouter.com/api/utils/matchPath # matchPath * Framework * Data * Declarative ## Summary Reference Documentation ↗ Performs pattern matching on a URL pathname and returns information about the match. ## Signature matchPath(pattern, pathname): undefined ## Params ### pattern * * * _No documentation_ ### pathname * * * _No documentation_ --- ## Page: https://reactrouter.com/api/utils/matchRoutes # matchRoutes * Framework * Data * Declarative ## Summary Reference Documentation ↗ Matches the given routes to a location and returns the match data. ## Signature matchRoutes(routes, locationArg, basename): undefined ## Params ### routes * * * _No documentation_ ### locationArg * * * _No documentation_ ### basename * * * _No documentation_ --- ## Page: https://reactrouter.com/api/utils/parsePath # parsePath * Framework * Data * Declarative ## Summary Reference Documentation ↗ Parses a string URL path into its separate pathname, search, and hash components. ## Signature parsePath(path): Partial ## Params ### path * * * _No documentation_ --- ## Page: https://reactrouter.com/api/utils/redirect # redirect * Framework * Data * Declarative ## Summary Reference Documentation ↗ A redirect response. Sets the status code and the `Location` header. Defaults to "302 Found". ## Signature redirect(url, init): Response ## Params ### url * * * _No documentation_ ### init * * * _No documentation_ --- ## Page: https://reactrouter.com/api/utils/redirectDocument # redirectDocument * Framework * Data * Declarative ## Summary Reference Documentation ↗ 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". ## Signature redirectDocument(url, init): Response ## Params ### url * * * _No documentation_ ### init * * * _No documentation_ --- ## Page: https://reactrouter.com/api/utils/renderMatches # renderMatches * Framework * Data * Declarative ## Summary Reference Documentation ↗ Renders the result of `matchRoutes()` into a React element. ## Signature renderMatches(matches): undefined ## Params ### matches * * * _No documentation_ --- ## Page: https://reactrouter.com/api/utils/replace # replace * Framework * Data * Declarative ## Summary Reference Documentation ↗ A redirect response that will perform a `history.replaceState` instead of a `history.pushState` for client-side navigation redirects. Sets the status code and the `Location` header. Defaults to "302 Found". ## Signature replace(url, init): Response ## Params ### url * * * _No documentation_ ### init * * * _No documentation_ --- ## Page: https://reactrouter.com/api/utils/resolvePath # resolvePath * Framework * Data * Declarative ## Summary Reference Documentation ↗ Returns a resolved path object relative to the given pathname. ## Signature resolvePath(to, fromPathname): Path ## Params ### to * * * _No documentation_ ### fromPathname * * * _No documentation_