Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-router

Package Overview
Dependencies
Maintainers
3
Versions
591
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-router - npm Package Compare versions

Comparing version 0.0.0-experimental-4a8a492a to 0.0.0-experimental-4b431ca46

dist/dom-export.d.ts

650

CHANGELOG.md
# `react-router`
## 7.0.0-pre.0
### Major Changes
- Remove the original `defer` implementation in favor of using raw promises via single fetch and `turbo-stream`. This removes these exports from React Router: ([#11744](https://github.com/remix-run/react-router/pull/11744))
- `defer`
- `AbortedDeferredError`
- `type TypedDeferredData`
- `UNSAFE_DeferredData`
- `UNSAFE_DEFERRED_SYMBOL`,
- - Collapse `@remix-run/router` into `react-router` ([#11505](https://github.com/remix-run/react-router/pull/11505))
- Collapse `react-router-dom` into `react-router`
- Collapse `@remix-run/server-runtime` into `react-router`
- Collapse `@remix-run/testing` into `react-router`
- Remove single_fetch future flag. ([#11522](https://github.com/remix-run/react-router/pull/11522))
- Drop support for Node 16, React Router SSR now requires Node 18 or higher ([#11391](https://github.com/remix-run/react-router/pull/11391))
- Remove `future.v7_startTransition` flag ([#11696](https://github.com/remix-run/react-router/pull/11696))
- - Expose the underlying router promises from the following APIs for compsition in React 19 APIs: ([#11521](https://github.com/remix-run/react-router/pull/11521))
- `useNavigate()`
- `useSubmit`
- `useFetcher().load`
- `useFetcher().submit`
- `useRevalidator.revalidate`
- Remove `future.v7_normalizeFormMethod` future flag ([#11697](https://github.com/remix-run/react-router/pull/11697))
- For Remix consumers migrating to React Router, the `crypto` global from the [Web Crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API) is now required when using cookie and session APIs. This means that the following APIs are provided from `react-router` rather than platform-specific packages: ([#11837](https://github.com/remix-run/react-router/pull/11837))
- `createCookie`
- `createCookieSessionStorage`
- `createMemorySessionStorage`
- `createSessionStorage`
For consumers running older versions of Node, the `installGlobals` function from `@remix-run/node` has been updated to define `globalThis.crypto`, using [Node's `require('node:crypto').webcrypto` implementation.](https://nodejs.org/api/webcrypto.html)
Since platform-specific packages no longer need to implement this API, the following low-level APIs have been removed:
- `createCookieFactory`
- `createSessionStorageFactory`
- `createCookieSessionStorageFactory`
- `createMemorySessionStorageFactory`
- Imports/Exports cleanup ([#11840](https://github.com/remix-run/react-router/pull/11840))
- Removed the following exports that were previously public API from `@remix-run/router`
- types
- `AgnosticDataIndexRouteObject`
- `AgnosticDataNonIndexRouteObject`
- `AgnosticDataRouteMatch`
- `AgnosticDataRouteObject`
- `AgnosticIndexRouteObject`
- `AgnosticNonIndexRouteObject`
- `AgnosticRouteMatch`
- `AgnosticRouteObject`
- `TrackedPromise`
- `unstable_AgnosticPatchRoutesOnMissFunction`
- `Action` -> exported as `NavigationType` via `react-router`
- `Router` exported as `RemixRouter` to differentiate from RR's `<Router>`
- API
- `getToPathname` (`@private`)
- `joinPaths` (`@private`)
- `normalizePathname` (`@private`)
- `resolveTo` (`@private`)
- `stripBasename` (`@private`)
- `createBrowserHistory` -> in favor of `createBrowserRouter`
- `createHashHistory` -> in favor of `createHashRouter`
- `createMemoryHistory` -> in favor of `createMemoryRouter`
- `createRouter`
- `createStaticHandler` -> in favor of wrapper `createStaticHandler` in RR Dom
- `getStaticContextFromError`
- Removed the following exports that were previously public API from `react-router`
- `Hash`
- `Pathname`
- `Search`
- update minimum node version to 18 ([#11690](https://github.com/remix-run/react-router/pull/11690))
- Remove `future.v7_prependBasename` from the ionternalized `@remix-run/router` package ([#11726](https://github.com/remix-run/react-router/pull/11726))
- Remove `future.v7_throwAbortReason` from internalized `@remix-run/router` package ([#11728](https://github.com/remix-run/react-router/pull/11728))
- Add `exports` field to all packages ([#11675](https://github.com/remix-run/react-router/pull/11675))
- node package no longer re-exports from react-router ([#11702](https://github.com/remix-run/react-router/pull/11702))
- renamed RemixContext to FrameworkContext ([#11705](https://github.com/remix-run/react-router/pull/11705))
- updates the minimum React version to 18 ([#11689](https://github.com/remix-run/react-router/pull/11689))
- PrefetchPageDescriptor replaced by PageLinkDescriptor ([#11960](https://github.com/remix-run/react-router/pull/11960))
- - Remove the `future.v7_partialHydration` flag ([#11725](https://github.com/remix-run/react-router/pull/11725))
- This also removes the `<RouterProvider fallbackElement>` prop
- To migrate, move the `fallbackElement` to a `hydrateFallbackElement`/`HydrateFallback` on your root route
- Also worth nothing there is a related breaking changer with this future flag:
- Without `future.v7_partialHydration` (when using `fallbackElement`), `state.navigation` was populated during the initial load
- With `future.v7_partialHydration`, `state.navigation` remains in an `"idle"` state during the initial load
- Remove `v7_relativeSplatPath` future flag ([#11695](https://github.com/remix-run/react-router/pull/11695))
- Remove remaining future flags ([#11820](https://github.com/remix-run/react-router/pull/11820))
- React Router `v7_skipActionErrorRevalidation`
- Remix `v3_fetcherPersist`, `v3_relativeSplatPath`, `v3_throwAbortReason`
- rename createRemixStub to createRoutesStub ([#11692](https://github.com/remix-run/react-router/pull/11692))
- Remove `@remix-run/router` deprecated `detectErrorBoundary` option in favor of `mapRouteProperties` ([#11751](https://github.com/remix-run/react-router/pull/11751))
- Add `react-router/dom` subpath export to properly enable `react-dom` as an optional `peerDependency` ([#11851](https://github.com/remix-run/react-router/pull/11851))
- This ensures that we don't blindly `import ReactDOM from "react-dom"` in `<RouterProvider>` in order to access `ReactDOM.flushSync()`, since that would break `createMemoryRouter` use cases in non-DOM environments
- DOM environments should import from `react-router/dom` to get the proper component that makes `ReactDOM.flushSync()` available:
- If you are using the Vite plugin, use this in your `entry.client.tsx`:
- `import { HydratedRouter } from 'react-router/dom'`
- If you are not using the Vite plugin and are manually calling `createBrowserRouter`/`createHashRouter`:
- `import { RouterProvider } from "react-router/dom"`
- Remove `future.v7_fetcherPersist` flag ([#11731](https://github.com/remix-run/react-router/pull/11731))
### Minor Changes
- - Add support for `prerender` config in the React Router vite plugin, to support existing SSG use-cases ([#11539](https://github.com/remix-run/react-router/pull/11539))
- You can use the `prerender` config to pre-render your `.html` and `.data` files at build time and then serve them statically at runtime (either from a running server or a CDN)
- `prerender` can either be an array of string paths, or a function (sync or async) that returns an array of strings so that you can dynamically generate the paths by talking to your CMS, etc.
```ts
export default defineConfig({
plugins: [
reactRouter({
async prerender() {
let slugs = await fakeGetSlugsFromCms();
// Prerender these paths into `.html` files at build time, and `.data`
// files if they have loaders
return ["/", "/about", ...slugs.map((slug) => `/product/${slug}`)];
},
}),
tsconfigPaths(),
],
});
async function fakeGetSlugsFromCms() {
await new Promise((r) => setTimeout(r, 1000));
return ["shirt", "hat"];
}
```
- [REMOVE] Allow returning undefined from loaders/actions part 2 ([#12057](https://github.com/remix-run/react-router/pull/12057))
- This is a follow up to #11680 which missed some of the Remix codepaths
- Params, loader data, and action data as props for route component exports ([#11961](https://github.com/remix-run/react-router/pull/11961))
```tsx
export default function Component({ params, loaderData, actionData }) {}
export function HydrateFallback({ params }) {}
export function ErrorBoundary({ params, loaderData, actionData }) {}
```
- Remove duplicate `RouterProvider` impliementations ([#11679](https://github.com/remix-run/react-router/pull/11679))
- ### Typesafety improvements ([#12019](https://github.com/remix-run/react-router/pull/12019))
React Router now generates types for each of your route modules.
You can access those types by importing them from `./+types/<route filename without extension>`.
For example:
```ts
// app/routes/product.tsx
import type * as Route from "./+types/product";
export function loader({ params }: Route.LoaderArgs) {}
export default function Component({ loaderData }: Route.ComponentProps) {}
```
This initial implementation targets type inference for:
- `Params` : Path parameters from your routing config in `routes.ts` including file-based routing
- `LoaderData` : Loader data from `loader` and/or `clientLoader` within your route module
- `ActionData` : Action data from `action` and/or `clientAction` within your route module
These types are then used to create types for route export args and props:
- `LoaderArgs`
- `ClientLoaderArgs`
- `ActionArgs`
- `ClientActionArgs`
- `HydrateFallbackProps`
- `ComponentProps` (for the `default` export)
- `ErrorBoundaryProps`
In the future, we plan to add types for the rest of the route module exports: `meta`, `links`, `headers`, `shouldRevalidate`, etc.
We also plan to generate types for typesafe `Link`s:
```tsx
<Link to="/products/:id" params={{ id: 1 }} />
// ^^^^^^^^^^^^^ ^^^^^^^^^
// typesafe `to` and `params` based on the available routes in your app
```
#### Setup
React Router will generate types into a `.react-router/` directory at the root of your app.
This directory is fully managed by React Router and is derived based on your route config (`routes.ts`).
👉 **Add `.react-router/` to `.gitignore`**
```txt
.react-router
```
You should also ensure that generated types for routes are always present before running typechecking,
especially for running typechecking in CI.
👉 **Add `react-router typegen` to your `typecheck` command in `package.json`**
```json
{
"scripts": {
"typecheck": "react-router typegen && tsc"
}
}
```
To get TypeScript to use those generated types, you'll need to add them to `include` in `tsconfig.json`.
And to be able to import them as if they files next to your route modules, you'll also need to configure `rootDirs`.
👉 **Configure `tsconfig.json` for generated types**
```json
{
"include": [".react-router/types/**/*"],
"compilerOptions": {
"rootDirs": [".", "./.react-router/types"]
}
}
```
#### `typegen` command
You can manually generate types with the new `typegen` command:
```sh
react-router typegen
```
However, manual type generation is tedious and types can get out of sync quickly if you ever forget to run `typegen`.
Instead, we recommend that you setup our new TypeScript plugin which will automatically generate fresh types whenever routes change.
That way, you'll always have up-to-date types.
#### TypeScript plugin
To get automatic type generation, you can use our new TypeScript plugin.
👉 **Add the TypeScript plugin to `tsconfig.json`**
```json
{
"compilerOptions": {
"plugins": [{ "name": "@react-router/dev" }]
}
}
```
We plan to add some other goodies to our TypeScript plugin soon, including:
- Automatic `jsdoc` for route exports that include links to official docs
- Autocomplete for route exports
- Warnings for non-HMR compliant exports
##### VSCode
TypeScript looks for plugins registered in `tsconfig.json` in the local `node_modules/`,
but VSCode ships with its own copy of TypeScript that is installed outside of your project.
For TypeScript plugins to work, you'll need to tell VSCode to use the local workspace version of TypeScript.
For security reasons, [VSCode won't use the workspace version of TypeScript](https://code.visualstudio.com/docs/typescript/typescript-compiling#_using-the-workspace-version-of-typescript) until you manually opt-in.
Your project should have a `.vscode/settings.json` with the following settings:
```json
{
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true
}
```
That way [VSCode will ask you](https://code.visualstudio.com/updates/v1_45#_prompt-users-to-switch-to-the-workspace-version-of-typescript) if you want to use the workspace version of TypeScript the first time you open a TS file in that project.
> [!IMPORTANT]
> You'll need to install dependencies first so that the workspace version of TypeScript is available.
👉 **Select "Allow" when VSCode asks if you want to use the workspace version of TypeScript**
Otherwise, you can also manually opt-in to the workspace version:
1. Open up any TypeScript file in your project
2. Open up the VSCode Command Palette (<kbd>Cmd</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd>)
3. Search for `Select TypeScript Version`
4. Choose `Use Workspace Version`
5. Quit and reopen VSCode
##### Troubleshooting
In VSCode, open up any TypeScript file in your project and then use <kbd>CMD</kbd>+<kbd>SHIFT</kbd>+<kbd>P</kbd> to select `Open TS Server log`.
There should be a log for `[react-router] setup` that indicates that the plugin was resolved correctly.
Then look for any errors in the log.
- Stabilize `unstable_dataStrategy` ([#11969](https://github.com/remix-run/react-router/pull/11969))
- Stabilize `unstable_patchRoutesOnNavigation` ([#11970](https://github.com/remix-run/react-router/pull/11970))
### Patch Changes
- Remove unstable upload handler. ([#12015](https://github.com/remix-run/react-router/pull/12015))
- Fix redirects returned from loaders/actions using `data()` ([#12021](https://github.com/remix-run/react-router/pull/12021))
- Updated dependencies:
- `react-router@7.0.0-pre.0`
## 6.26.2
### Patch Changes
- Updated dependencies:
- `@remix-run/router@1.19.2`
## 6.26.1
### Patch Changes
- Rename `unstable_patchRoutesOnMiss` to `unstable_patchRoutesOnNavigation` to match new behavior ([#11888](https://github.com/remix-run/react-router/pull/11888))
- Updated dependencies:
- `@remix-run/router@1.19.1`
## 6.26.0
### Minor Changes
- Add a new `replace(url, init?)` alternative to `redirect(url, init?)` that performs a `history.replaceState` instead of a `history.pushState` on client-side navigation redirects ([#11811](https://github.com/remix-run/react-router/pull/11811))
### Patch Changes
- Fix initial hydration behavior when using `future.v7_partialHydration` along with `unstable_patchRoutesOnMiss` ([#11838](https://github.com/remix-run/react-router/pull/11838))
- During initial hydration, `router.state.matches` will now include any partial matches so that we can render ancestor `HydrateFallback` components
- Updated dependencies:
- `@remix-run/router@1.19.0`
## 6.25.1
No significant changes to this package were made in this release. [See the repo `CHANGELOG.md`](https://github.com/remix-run/react-router/blob/main/CHANGELOG.md) for an overview of all changes in v6.25.1.
## 6.25.0
### Minor Changes
- Stabilize `future.unstable_skipActionErrorRevalidation` as `future.v7_skipActionErrorRevalidation` ([#11769](https://github.com/remix-run/react-router/pull/11769))
- When this flag is enabled, actions will not automatically trigger a revalidation if they return/throw a `Response` with a `4xx`/`5xx` status code
- You may still opt-into revalidation via `shouldRevalidate`
- This also changes `shouldRevalidate`'s `unstable_actionStatus` parameter to `actionStatus`
### Patch Changes
- Fix regression and properly decode paths inside `useMatch` so matches/params reflect decoded params ([#11789](https://github.com/remix-run/react-router/pull/11789))
- Updated dependencies:
- `@remix-run/router@1.18.0`
## 6.24.1
### Patch Changes
- When using `future.v7_relativeSplatPath`, properly resolve relative paths in splat routes that are children of pathless routes ([#11633](https://github.com/remix-run/react-router/pull/11633))
- Updated dependencies:
- `@remix-run/router@1.17.1`
## 6.24.0
### Minor Changes
- Add support for Lazy Route Discovery (a.k.a. Fog of War) ([#11626](https://github.com/remix-run/react-router/pull/11626))
- RFC: <https://github.com/remix-run/react-router/discussions/11113>
- `unstable_patchRoutesOnMiss` docs: <https://reactrouter.com/en/main/routers/create-browser-router>
### Patch Changes
- Updated dependencies:
- `@remix-run/router@1.17.0`
## 6.23.1
### Patch Changes
- allow undefined to be resolved with `<Await>` ([#11513](https://github.com/remix-run/react-router/pull/11513))
- Updated dependencies:
- `@remix-run/router@1.16.1`
## 6.23.0
### Minor Changes
- Add a new `unstable_dataStrategy` configuration option ([#11098](https://github.com/remix-run/react-router/pull/11098))
- This option allows Data Router applications to take control over the approach for executing route loaders and actions
- The default implementation is today's behavior, to fetch all loaders in parallel, but this option allows users to implement more advanced data flows including Remix single-fetch, middleware/context APIs, automatic loader caching, and more
### Patch Changes
- Updated dependencies:
- `@remix-run/router@1.16.0`
## 6.22.3
### Patch Changes
- Updated dependencies:
- `@remix-run/router@1.15.3`
## 6.22.2
### Patch Changes
- Updated dependencies:
- `@remix-run/router@1.15.2`
## 6.22.1
### Patch Changes
- Fix encoding/decoding issues with pre-encoded dynamic parameter values ([#11199](https://github.com/remix-run/react-router/pull/11199))
- Updated dependencies:
- `@remix-run/router@1.15.1`
## 6.22.0
### Patch Changes
- Updated dependencies:
- `@remix-run/router@1.15.0`
## 6.21.3
### Patch Changes
- Remove leftover `unstable_` prefix from `Blocker`/`BlockerFunction` types ([#11187](https://github.com/remix-run/react-router/pull/11187))
## 6.21.2
### Patch Changes
- Updated dependencies:
- `@remix-run/router@1.14.2`
## 6.21.1
### Patch Changes
- Fix bug with `route.lazy` not working correctly on initial SPA load when `v7_partialHydration` is specified ([#11121](https://github.com/remix-run/react-router/pull/11121))
- Updated dependencies:
- `@remix-run/router@1.14.1`
## 6.21.0
### Minor Changes
- Add a new `future.v7_relativeSplatPath` flag to implement a breaking bug fix to relative routing when inside a splat route. ([#11087](https://github.com/remix-run/react-router/pull/11087))
This fix was originally added in [#10983](https://github.com/remix-run/react-router/issues/10983) and was later reverted in [#11078](https://github.com/remix-run/react-router/pull/11078) because it was determined that a large number of existing applications were relying on the buggy behavior (see [#11052](https://github.com/remix-run/react-router/issues/11052))
**The Bug**
The buggy behavior is that without this flag, the default behavior when resolving relative paths is to _ignore_ any splat (`*`) portion of the current route path.
**The Background**
This decision was originally made thinking that it would make the concept of nested different sections of your apps in `<Routes>` easier if relative routing would _replace_ the current splat:
```jsx
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="dashboard/*" element={<Dashboard />} />
</Routes>
</BrowserRouter>
```
Any paths like `/dashboard`, `/dashboard/team`, `/dashboard/projects` will match the `Dashboard` route. The dashboard component itself can then render nested `<Routes>`:
```jsx
function Dashboard() {
return (
<div>
<h2>Dashboard</h2>
<nav>
<Link to="/">Dashboard Home</Link>
<Link to="team">Team</Link>
<Link to="projects">Projects</Link>
</nav>
<Routes>
<Route path="/" element={<DashboardHome />} />
<Route path="team" element={<DashboardTeam />} />
<Route path="projects" element={<DashboardProjects />} />
</Routes>
</div>
);
}
```
Now, all links and route paths are relative to the router above them. This makes code splitting and compartmentalizing your app really easy. You could render the `Dashboard` as its own independent app, or embed it into your large app without making any changes to it.
**The Problem**
The problem is that this concept of ignoring part of a path breaks a lot of other assumptions in React Router - namely that `"."` always means the current location pathname for that route. When we ignore the splat portion, we start getting invalid paths when using `"."`:
```jsx
// If we are on URL /dashboard/team, and we want to link to /dashboard/team:
function DashboardTeam() {
// ❌ This is broken and results in <a href="/dashboard">
return <Link to=".">A broken link to the Current URL</Link>;
// ✅ This is fixed but super unintuitive since we're already at /dashboard/team!
return <Link to="./team">A broken link to the Current URL</Link>;
}
```
We've also introduced an issue that we can no longer move our `DashboardTeam` component around our route hierarchy easily - since it behaves differently if we're underneath a non-splat route, such as `/dashboard/:widget`. Now, our `"."` links will, properly point to ourself _inclusive of the dynamic param value_ so behavior will break from it's corresponding usage in a `/dashboard/*` route.
Even worse, consider a nested splat route configuration:
```jsx
<BrowserRouter>
<Routes>
<Route path="dashboard">
<Route path="*" element={<Dashboard />} />
</Route>
</Routes>
</BrowserRouter>
```
Now, a `<Link to=".">` and a `<Link to="..">` inside the `Dashboard` component go to the same place! That is definitely not correct!
Another common issue arose in Data Routers (and Remix) where any `<Form>` should post to it's own route `action` if you the user doesn't specify a form action:
```jsx
let router = createBrowserRouter({
path: "/dashboard",
children: [
{
path: "*",
action: dashboardAction,
Component() {
// ❌ This form is broken! It throws a 405 error when it submits because
// it tries to submit to /dashboard (without the splat value) and the parent
// `/dashboard` route doesn't have an action
return <Form method="post">...</Form>;
},
},
],
});
```
This is just a compounded issue from the above because the default location for a `Form` to submit to is itself (`"."`) - and if we ignore the splat portion, that now resolves to the parent route.
**The Solution**
If you are leveraging this behavior, it's recommended to enable the future flag, move your splat to it's own route, and leverage `../` for any links to "sibling" pages:
```jsx
<BrowserRouter>
<Routes>
<Route path="dashboard">
<Route index path="*" element={<Dashboard />} />
</Route>
</Routes>
</BrowserRouter>
function Dashboard() {
return (
<div>
<h2>Dashboard</h2>
<nav>
<Link to="..">Dashboard Home</Link>
<Link to="../team">Team</Link>
<Link to="../projects">Projects</Link>
</nav>
<Routes>
<Route path="/" element={<DashboardHome />} />
<Route path="team" element={<DashboardTeam />} />
<Route path="projects" element={<DashboardProjects />} />
</Router>
</div>
);
}
```
This way, `.` means "the full current pathname for my route" in all cases (including static, dynamic, and splat routes) and `..` always means "my parents pathname".
### Patch Changes
- Properly handle falsy error values in ErrorBoundary's ([#11071](https://github.com/remix-run/react-router/pull/11071))
- Updated dependencies:
- `@remix-run/router@1.14.0`
## 6.20.1
### Patch Changes
- Revert the `useResolvedPath` fix for splat routes due to a large number of applications that were relying on the buggy behavior (see <https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329>). We plan to re-introduce this fix behind a future flag in the next minor version. ([#11078](https://github.com/remix-run/react-router/pull/11078))
- Updated dependencies:
- `@remix-run/router@1.13.1`
## 6.20.0
### Minor Changes
- Export the `PathParam` type from the public API ([#10719](https://github.com/remix-run/react-router/pull/10719))
### Patch Changes
- Fix bug with `resolveTo` in splat routes ([#11045](https://github.com/remix-run/react-router/pull/11045))
- This is a follow up to [#10983](https://github.com/remix-run/react-router/pull/10983) to handle the few other code paths using `getPathContributingMatches`
- This removes the `UNSAFE_getPathContributingMatches` export from `@remix-run/router` since we no longer need this in the `react-router`/`react-router-dom` layers
- Updated dependencies:
- `@remix-run/router@1.13.0`
## 6.19.0
### Minor Changes
- Add `unstable_flushSync` option to `useNavigate`/`useSumbit`/`fetcher.load`/`fetcher.submit` to opt-out of `React.startTransition` and into `ReactDOM.flushSync` for state updates ([#11005](https://github.com/remix-run/react-router/pull/11005))
- Remove the `unstable_` prefix from the [`useBlocker`](https://reactrouter.com/en/main/hooks/use-blocker) hook as it's been in use for enough time that we are confident in the API. We do not plan to remove the prefix from `unstable_usePrompt` due to differences in how browsers handle `window.confirm` that prevent React Router from guaranteeing consistent/correct behavior. ([#10991](https://github.com/remix-run/react-router/pull/10991))
### Patch Changes
- Fix `useActionData` so it returns proper contextual action data and not _any_ action data in the tree ([#11023](https://github.com/remix-run/react-router/pull/11023))
- Fix bug in `useResolvedPath` that would cause `useResolvedPath(".")` in a splat route to lose the splat portion of the URL path. ([#10983](https://github.com/remix-run/react-router/pull/10983))
- ⚠️ This fixes a quite long-standing bug specifically for `"."` paths inside a splat route which incorrectly dropped the splat portion of the URL. If you are relative routing via `"."` inside a splat route in your application you should double check that your logic is not relying on this buggy behavior and update accordingly.
- Updated dependencies:
- `@remix-run/router@1.12.0`
## 6.18.0
### Patch Changes
- Fix the `future` prop on `BrowserRouter`, `HashRouter` and `MemoryRouter` so that it accepts a `Partial<FutureConfig>` instead of requiring all flags to be included. ([#10962](https://github.com/remix-run/react-router/pull/10962))
- Updated dependencies:
- `@remix-run/router@1.11.0`
## 6.17.0
### Patch Changes
- Fix `RouterProvider` `future` prop type to be a `Partial<FutureConfig>` so that not all flags must be specified ([#10900](https://github.com/remix-run/react-router/pull/10900))
- Updated dependencies:
- `@remix-run/router@1.10.0`
## 6.16.0

@@ -92,3 +734,3 @@

> **Warning**
> \[!WARNING]
> Please use version `6.13.0` or later instead of `6.12.1`. This version suffers from a `webpack`/`terser` minification issue resulting in invalid minified code in your resulting production bundles which can cause issues in your application. See [#10579](https://github.com/remix-run/react-router/issues/10579) for more details.

@@ -425,3 +1067,3 @@

Whoa this is a big one! `6.4.0` brings all the data loading and mutation APIs over from Remix. Here's a quick high level overview, but it's recommended you go check out the [docs][rr-docs], especially the [feature overview][rr-feature-overview] and the [tutorial][rr-tutorial].
Whoa this is a big one! `6.4.0` brings all the data loading and mutation APIs over from Remix. Here's a quick high level overview, but it's recommended you go check out the [docs](https://reactrouter.com), especially the [feature overview](https://reactrouter.com/start/overview) and the [tutorial](https://reactrouter.com/start/tutorial).

@@ -444,5 +1086,1 @@ **New APIs**

- `@remix-run/router@1.0.0`
[rr-docs]: https://reactrouter.com
[rr-feature-overview]: https://reactrouter.com/start/overview
[rr-tutorial]: https://reactrouter.com/start/tutorial

97

dist/index.d.ts

@@ -1,25 +0,74 @@

import type { ActionFunction, ActionFunctionArgs, Blocker, BlockerFunction, ErrorResponse, Fetcher, HydrationState, InitialEntry, JsonFunction, LazyRouteFunction, LoaderFunction, LoaderFunctionArgs, Location, Navigation, ParamParseKey, Params, Path, PathMatch, PathPattern, RedirectFunction, RelativeRoutingType, Router as RemixRouter, FutureConfig as RouterFutureConfig, ShouldRevalidateFunction, ShouldRevalidateFunctionArgs, To, UIMatch } from "@remix-run/router";
import { AbortedDeferredError, Action as NavigationType, createPath, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, redirectDocument, resolvePath } from "@remix-run/router";
import type { AwaitProps, FutureConfig, IndexRouteProps, LayoutRouteProps, MemoryRouterProps, NavigateProps, OutletProps, PathRouteProps, RouteProps, RouterProps, RouterProviderProps, RoutesProps } from "./lib/components";
import { Await, MemoryRouter, Navigate, Outlet, Route, Router, RouterProvider, Routes, createRoutesFromChildren, renderMatches } from "./lib/components";
import type { DataRouteMatch, DataRouteObject, IndexRouteObject, NavigateOptions, Navigator, NonIndexRouteObject, RouteMatch, RouteObject } from "./lib/context";
import { DataRouterContext, DataRouterStateContext, LocationContext, NavigationContext, RouteContext, ViewTransitionContext } from "./lib/context";
import type { NavigateFunction } from "./lib/hooks";
import { useActionData, useAsyncError, useAsyncValue, useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteId, useRouteLoaderData, useRoutes, useRoutesImpl } from "./lib/hooks";
type Hash = string;
type Pathname = string;
type Search = string;
export type { ActionFunction, ActionFunctionArgs, AwaitProps, DataRouteMatch, DataRouteObject, ErrorResponse, Fetcher, FutureConfig, Hash, IndexRouteObject, IndexRouteProps, JsonFunction, LayoutRouteProps, LazyRouteFunction, LoaderFunction, LoaderFunctionArgs, Location, MemoryRouterProps, NavigateFunction, NavigateOptions, NavigateProps, Navigation, Navigator, NonIndexRouteObject, OutletProps, ParamParseKey, Params, Path, PathMatch, PathPattern, PathRouteProps, Pathname, RedirectFunction, RelativeRoutingType, RouteMatch, RouteObject, RouteProps, RouterProps, RouterProviderProps, RoutesProps, Search, ShouldRevalidateFunction, ShouldRevalidateFunctionArgs, To, UIMatch, Blocker as unstable_Blocker, BlockerFunction as unstable_BlockerFunction, };
export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, RouterProvider, Routes, createPath, createRoutesFromChildren, createRoutesFromChildren as createRoutesFromElements, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, redirectDocument, renderMatches, resolvePath, useBlocker as unstable_useBlocker, useActionData, useAsyncError, useAsyncValue, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes, };
declare function mapRouteProperties(route: RouteObject): Partial<RouteObject> & {
hasErrorBoundary: boolean;
};
export declare function createMemoryRouter(routes: RouteObject[], opts?: {
basename?: string;
future?: Partial<Omit<RouterFutureConfig, "v7_prependBasename">>;
hydrationData?: HydrationState;
initialEntries?: InitialEntry[];
initialIndex?: number;
}): RemixRouter;
export type { InitialEntry, Location, Path, To } from "./lib/router/history";
export type { HydrationState, StaticHandler, GetScrollPositionFunction, GetScrollRestorationKeyFunction, StaticHandlerContext, Fetcher, Navigation, NavigationStates, RelativeRoutingType, Blocker, BlockerFunction, Router as RemixRouter, RouterState, RouterInit, RouterSubscriber, RouterNavigateOptions, RouterFetchOptions, RevalidationState, } from "./lib/router/router";
export type { ActionFunction, ActionFunctionArgs, DataStrategyFunction, DataStrategyFunctionArgs, DataStrategyMatch, DataStrategyResult, DataWithResponseInit as UNSAFE_DataWithResponseInit, ErrorResponse, FormEncType, FormMethod, HTMLFormMethod, JsonFunction, LazyRouteFunction, LoaderFunction, LoaderFunctionArgs, ParamParseKey, Params, PathMatch, PathParam, PathPattern, RedirectFunction, ShouldRevalidateFunction, ShouldRevalidateFunctionArgs, UIMatch, } from "./lib/router/utils";
export { Action as NavigationType, createPath, parsePath, } from "./lib/router/history";
export { IDLE_NAVIGATION, IDLE_FETCHER, IDLE_BLOCKER, } from "./lib/router/router";
export { data, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, redirect, redirectDocument, replace, resolvePath, } from "./lib/router/utils";
export type { DataRouteMatch, DataRouteObject, IndexRouteObject, NavigateOptions, Navigator, NonIndexRouteObject, PatchRoutesOnNavigationFunction, PatchRoutesOnNavigationFunctionArgs, RouteMatch, RouteObject, } from "./lib/context";
export type { AwaitProps, IndexRouteProps, LayoutRouteProps, MemoryRouterProps, NavigateProps, OutletProps, PathRouteProps, RouteProps, RouterProps, RouterProviderProps, RoutesProps, } from "./lib/components";
export type { NavigateFunction } from "./lib/hooks";
export { Await, MemoryRouter, Navigate, Outlet, Route, Router, RouterProvider, Routes, createMemoryRouter, createRoutesFromChildren, createRoutesFromChildren as createRoutesFromElements, renderMatches, } from "./lib/components";
export { useBlocker, useActionData, useAsyncError, useAsyncValue, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes, } from "./lib/hooks";
export type { BrowserRouterProps, HashRouterProps, HistoryRouterProps, LinkProps, NavLinkProps, NavLinkRenderProps, FetcherFormProps, FormProps, ScrollRestorationProps, SetURLSearchParams, SubmitFunction, FetcherSubmitFunction, FetcherWithComponents, } from "./lib/dom/lib";
export { createBrowserRouter, createHashRouter, BrowserRouter, HashRouter, Link, HistoryRouter as unstable_HistoryRouter, NavLink, Form, ScrollRestoration, useLinkClickHandler, useSearchParams, useSubmit, useFormAction, useFetcher, useFetchers, useBeforeUnload, usePrompt as unstable_usePrompt, useViewTransitionState, } from "./lib/dom/lib";
export type { FetcherSubmitOptions, ParamKeyValuePair, SubmitOptions, URLSearchParamsInit, SubmitTarget, } from "./lib/dom/dom";
export { createSearchParams } from "./lib/dom/dom";
export type { StaticRouterProps, StaticRouterProviderProps, } from "./lib/dom/server";
export { createStaticHandler, createStaticRouter, StaticRouter, StaticRouterProvider, } from "./lib/dom/server";
export { Meta, Links, Scripts, PrefetchPageLinks, } from "./lib/dom/ssr/components";
export type { ScriptsProps } from "./lib/dom/ssr/components";
export type { EntryContext } from "./lib/dom/ssr/entry";
export type { ClientActionFunction, ClientActionFunctionArgs, ClientLoaderFunction, ClientLoaderFunctionArgs, MetaArgs, MetaDescriptor, MetaFunction, LinksFunction, } from "./lib/dom/ssr/routeModules";
export type { ServerRouterProps } from "./lib/dom/ssr/server";
export { ServerRouter } from "./lib/dom/ssr/server";
export type { RoutesTestStubProps } from "./lib/dom/ssr/routes-test-stub";
export { createRoutesStub } from "./lib/dom/ssr/routes-test-stub";
export { createCookie, isCookie } from "./lib/server-runtime/cookies";
export { createRequestHandler } from "./lib/server-runtime/server";
export { createSession, createSessionStorage, isSession, } from "./lib/server-runtime/sessions";
export { createCookieSessionStorage } from "./lib/server-runtime/sessions/cookieStorage";
export { createMemorySessionStorage } from "./lib/server-runtime/sessions/memoryStorage";
export { setDevServerHooks as unstable_setDevServerHooks } from "./lib/server-runtime/dev";
export type { IsCookieFunction } from "./lib/server-runtime/cookies";
export type { CreateRequestHandlerFunction } from "./lib/server-runtime/server";
export type { IsSessionFunction } from "./lib/server-runtime/sessions";
export type { HandleDataRequestFunction, HandleDocumentRequestFunction, HandleErrorFunction, ServerBuild, ServerEntryModule, } from "./lib/server-runtime/build";
export type { Cookie, CookieOptions, CookieParseOptions, CookieSerializeOptions, CookieSignatureOptions, } from "./lib/server-runtime/cookies";
export type { AppLoadContext } from "./lib/server-runtime/data";
export type { PageLinkDescriptor, HtmlLinkDescriptor, LinkDescriptor, } from "./lib/router/links";
export type { TypedResponse } from "./lib/server-runtime/responses";
export type { DataFunctionArgs, HeadersArgs, HeadersFunction, } from "./lib/server-runtime/routeModules";
export type { RequestHandler } from "./lib/server-runtime/server";
export type { Session, SessionData, SessionIdStorageStrategy, SessionStorage, FlashSessionData, } from "./lib/server-runtime/sessions";
/** @internal */
export { DataRouterContext as UNSAFE_DataRouterContext, DataRouterStateContext as UNSAFE_DataRouterStateContext, LocationContext as UNSAFE_LocationContext, NavigationContext as UNSAFE_NavigationContext, RouteContext as UNSAFE_RouteContext, ViewTransitionContext as UNSAFE_ViewTransitionContext, mapRouteProperties as UNSAFE_mapRouteProperties, useRouteId as UNSAFE_useRouteId, useRoutesImpl as UNSAFE_useRoutesImpl, };
export { createBrowserHistory as UNSAFE_createBrowserHistory, invariant as UNSAFE_invariant, } from "./lib/router/history";
/** @internal */
export { createRouter as UNSAFE_createRouter } from "./lib/router/router";
/** @internal */
export { ErrorResponseImpl as UNSAFE_ErrorResponseImpl } from "./lib/router/utils";
/** @internal */
export { DataRouterContext as UNSAFE_DataRouterContext, DataRouterStateContext as UNSAFE_DataRouterStateContext, FetchersContext as UNSAFE_FetchersContext, LocationContext as UNSAFE_LocationContext, NavigationContext as UNSAFE_NavigationContext, RouteContext as UNSAFE_RouteContext, ViewTransitionContext as UNSAFE_ViewTransitionContext, } from "./lib/context";
/** @internal */
export { mapRouteProperties as UNSAFE_mapRouteProperties } from "./lib/components";
/** @internal */
export { FrameworkContext as UNSAFE_FrameworkContext } from "./lib/dom/ssr/components";
/** @internal */
export type { AssetsManifest as UNSAFE_AssetsManifest } from "./lib/dom/ssr/entry";
/** @internal */
export { deserializeErrors as UNSAFE_deserializeErrors } from "./lib/dom/ssr/errors";
/** @internal */
export { RemixErrorBoundary as UNSAFE_RemixErrorBoundary } from "./lib/dom/ssr/errorBoundaries";
/** @internal */
export { getPatchRoutesOnNavigationFunction as UNSAFE_getPatchRoutesOnNavigationFunction, useFogOFWarDiscovery as UNSAFE_useFogOFWarDiscovery, } from "./lib/dom/ssr/fog-of-war";
/** @internal */
export type { RouteModules as UNSAFE_RouteModules } from "./lib/dom/ssr/routeModules";
/** @internal */
export { createClientRoutes as UNSAFE_createClientRoutes, createClientRoutesWithHMRRevalidationOptOut as UNSAFE_createClientRoutesWithHMRRevalidationOptOut, shouldHydrateRouteLoader as UNSAFE_shouldHydrateRouteLoader, } from "./lib/dom/ssr/routes";
/** @internal */
export { getSingleFetchDataStrategy as UNSAFE_getSingleFetchDataStrategy } from "./lib/dom/ssr/single-fetch";
/** @internal */
export { decodeViaTurboStream as UNSAFE_decodeViaTurboStream, SingleFetchRedirectSymbol as UNSAFE_SingleFetchRedirectSymbol, } from "./lib/dom/ssr/single-fetch";
/** @internal */
export { ServerMode as UNSAFE_ServerMode } from "./lib/server-runtime/mode";
/** @internal */
export { useScrollRestoration as UNSAFE_useScrollRestoration } from "./lib/dom/lib";

@@ -1,23 +0,28 @@

import type { InitialEntry, LazyRouteFunction, Location, RelativeRoutingType, Router as RemixRouter, To, TrackedPromise } from "@remix-run/router";
import { Action as NavigationType } from "@remix-run/router";
import * as React from "react";
import type { IndexRouteObject, Navigator, NonIndexRouteObject, RouteMatch, RouteObject } from "./context";
interface ViewTransition {
finished: Promise<void>;
ready: Promise<void>;
updateCallbackDone: Promise<void>;
skipTransition(): void;
}
declare global {
interface Document {
startViewTransition(cb: () => Promise<void> | void): ViewTransition;
}
}
export interface FutureConfig {
v7_startTransition: boolean;
}
import type { InitialEntry, Location, To } from "./router/history";
import { Action as NavigationType } from "./router/history";
import type { FutureConfig, HydrationState, RelativeRoutingType, Router as RemixRouter } from "./router/router";
import type { DataStrategyFunction, LazyRouteFunction, TrackedPromise } from "./router/utils";
import type { IndexRouteObject, Navigator, NonIndexRouteObject, PatchRoutesOnNavigationFunction, RouteMatch, RouteObject } from "./context";
/**
* @private
*/
export declare function mapRouteProperties(route: RouteObject): Partial<RouteObject> & {
hasErrorBoundary: boolean;
};
/**
* @category Routers
*/
export declare function createMemoryRouter(routes: RouteObject[], opts?: {
basename?: string;
future?: Partial<FutureConfig>;
hydrationData?: HydrationState;
initialEntries?: InitialEntry[];
initialIndex?: number;
dataStrategy?: DataStrategyFunction;
patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;
}): RemixRouter;
export interface RouterProviderProps {
fallbackElement?: React.ReactNode;
router: RemixRouter;
future?: FutureConfig;
flushSync?: (fn: () => unknown) => undefined;
}

@@ -27,3 +32,6 @@ /**

*/
export declare function RouterProvider({ fallbackElement, router, future, }: RouterProviderProps): React.ReactElement;
export declare function RouterProvider({ router, flushSync: reactDomFlushSyncImpl, }: RouterProviderProps): React.ReactElement;
/**
* @category Types
*/
export interface MemoryRouterProps {

@@ -34,3 +42,2 @@ basename?: string;

initialIndex?: number;
future?: FutureConfig;
}

@@ -40,5 +47,8 @@ /**

*
* @see https://reactrouter.com/router-components/memory-router
* @category Router Components
*/
export declare function MemoryRouter({ basename, children, initialEntries, initialIndex, future, }: MemoryRouterProps): React.ReactElement;
export declare function MemoryRouter({ basename, children, initialEntries, initialIndex, }: MemoryRouterProps): React.ReactElement;
/**
* @category Types
*/
export interface NavigateProps {

@@ -51,20 +61,48 @@ to: To;

/**
* Changes the current location.
* A component-based version of {@link useNavigate} to use in a [`React.Component
* Class`](https://reactjs.org/docs/react-component.html) where hooks are not
* able to be used.
*
* Note: This API is mostly useful in React.Component subclasses that are not
* able to use hooks. In functional components, we recommend you use the
* `useNavigate` hook instead.
* It's recommended to avoid using this component in favor of {@link useNavigate}
*
* @see https://reactrouter.com/components/navigate
* @category Components
*/
export declare function Navigate({ to, replace, state, relative, }: NavigateProps): null;
/**
* @category Types
*/
export interface OutletProps {
/**
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 {@link useOutletContext}.
*/
context?: unknown;
}
/**
* Renders the child route's element, if there is one.
*
* @see https://reactrouter.com/components/outlet
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 (
<div>
<h1>Parent Content</h1>
<Outlet />
</div>
);
}
```
@category Components
*/
export declare function Outlet(props: OutletProps): React.ReactElement | null;
/**
* @category Types
*/
export interface PathRouteProps {

@@ -83,8 +121,16 @@ caseSensitive?: NonIndexRouteObject["caseSensitive"];

element?: React.ReactNode | null;
hydrateFallbackElement?: React.ReactNode | null;
errorElement?: React.ReactNode | null;
Component?: React.ComponentType | null;
HydrateFallback?: React.ComponentType | null;
ErrorBoundary?: React.ComponentType | null;
}
/**
* @category Types
*/
export interface LayoutRouteProps extends PathRouteProps {
}
/**
* @category Types
*/
export interface IndexRouteProps {

@@ -103,4 +149,6 @@ caseSensitive?: IndexRouteObject["caseSensitive"];

element?: React.ReactNode | null;
hydrateFallbackElement?: React.ReactNode | null;
errorElement?: React.ReactNode | null;
Component?: React.ComponentType | null;
HydrateFallback?: React.ComponentType | null;
ErrorBoundary?: React.ComponentType | null;

@@ -110,7 +158,13 @@ }

/**
* Declares an element that should be rendered at a certain URL path.
* Configures an element to render when a pattern matches the current location.
* It must be rendered within a {@link Routes} element. Note that these routes
* do not participate in data loading, actions, code splitting, or any other
* route module features.
*
* @see https://reactrouter.com/components/route
* @category Components
*/
export declare function Route(_props: RouteProps): React.ReactElement | null;
/**
* @category Types
*/
export interface RouterProps {

@@ -131,14 +185,34 @@ basename?: string;

*
* @see https://reactrouter.com/router-components/router
* @category Components
*/
export declare function Router({ basename: basenameProp, children, location: locationProp, navigationType, navigator, static: staticProp, }: RouterProps): React.ReactElement | null;
/**
* @category Types
*/
export interface RoutesProps {
/**
* Nested {@link Route} elements
*/
children?: React.ReactNode;
/**
* The location to match against. Defaults to the current location.
*/
location?: Partial<Location> | string;
}
/**
* A container for a nested tree of `<Route>` elements that renders the branch
* that best matches the current location.
*
* @see https://reactrouter.com/components/routes
Renders a branch of {@link Route | `<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"
<Routes>
<Route index element={<StepOne />} />
<Route path="step-2" element={<StepTwo />} />
<Route path="step-3" element={<StepThree />}>
</Routes>
```
@category Components
*/

@@ -149,11 +223,145 @@ export declare function Routes({ children, location, }: RoutesProps): React.ReactElement | null;

}
/**
* @category Types
*/
export interface AwaitProps {
/**
When using a function, the resolved value is provided as the parameter.
```tsx [2]
<Await resolve={reviewsPromise}>
{(resolvedReviews) => <Reviews items={resolvedReviews} />}
</Await>
```
When using React elements, {@link useAsyncValue} will provide the
resolved value:
```tsx [2]
<Await resolve={reviewsPromise}>
<Reviews />
</Await>
function Reviews() {
const resolvedReviews = useAsyncValue()
return <div>...</div>
}
```
*/
children: React.ReactNode | AwaitResolveRenderFunction;
/**
The error element renders instead of the children when the promise rejects.
```tsx
<Await
errorElement={<div>Oops</div>}
resolve={reviewsPromise}
>
<Reviews />
</Await>
```
To provide a more contextual error, you can use the {@link useAsyncError} in a
child component
```tsx
<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 {@link NonIndexRouteObject#ErrorBoundary | ErrorBoundary} and be accessible
via {@link useRouteError} hook.
*/
errorElement?: React.ReactNode;
/**
Takes a promise returned from a {@link LoaderFunction | 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 (
<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>
);
}
```
*/
resolve: TrackedPromise | any;
}
/**
* Component to use for rendering lazily loaded data from returning defer()
* in a loader function
*/
Used to render promise values with automatic error handling.
```tsx
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>
);
}
```
**Note:** `<Await>` expects to be rendered inside of a `<React.Suspense>`
@category Components
*/
export declare function Await({ children, errorElement, resolve }: AwaitProps): React.JSX.Element;

@@ -165,3 +373,3 @@ /**

*
* @see https://reactrouter.com/utils/create-routes-from-children
* @category Utils
*/

@@ -171,4 +379,5 @@ export declare function createRoutesFromChildren(children: React.ReactNode, parentPath?: number[]): RouteObject[];

* Renders the result of `matchRoutes()` into a React element.
*
* @category Utils
*/
export declare function renderMatches(matches: RouteMatch[] | null): React.ReactElement | null;
export {};
import * as React from "react";
import type { AgnosticIndexRouteObject, AgnosticNonIndexRouteObject, AgnosticRouteMatch, History, LazyRouteFunction, Location, Action as NavigationType, RelativeRoutingType, Router, StaticHandlerContext, To, TrackedPromise } from "@remix-run/router";
import type { History, Action as NavigationType, Location, To } from "./router/history";
import type { RelativeRoutingType, Router, StaticHandlerContext } from "./router/router";
import type { AgnosticIndexRouteObject, AgnosticNonIndexRouteObject, AgnosticPatchRoutesOnNavigationFunction, AgnosticPatchRoutesOnNavigationFunctionArgs, AgnosticRouteMatch, LazyRouteFunction, TrackedPromise } from "./router/utils";
export interface IndexRouteObject {

@@ -15,4 +17,6 @@ caseSensitive?: AgnosticIndexRouteObject["caseSensitive"];

element?: React.ReactNode | null;
hydrateFallbackElement?: React.ReactNode | null;
errorElement?: React.ReactNode | null;
Component?: React.ComponentType | null;
HydrateFallback?: React.ComponentType | null;
ErrorBoundary?: React.ComponentType | null;

@@ -33,4 +37,6 @@ lazy?: LazyRouteFunction<RouteObject>;

element?: React.ReactNode | null;
hydrateFallbackElement?: React.ReactNode | null;
errorElement?: React.ReactNode | null;
Component?: React.ComponentType | null;
HydrateFallback?: React.ComponentType | null;
ErrorBoundary?: React.ComponentType | null;

@@ -48,3 +54,5 @@ lazy?: LazyRouteFunction<RouteObject>;

}
export interface DataRouterContextObject extends NavigationContextObject {
export type PatchRoutesOnNavigationFunctionArgs = AgnosticPatchRoutesOnNavigationFunctionArgs<RouteObject, RouteMatch>;
export type PatchRoutesOnNavigationFunction = AgnosticPatchRoutesOnNavigationFunction<RouteObject, RouteMatch>;
export interface DataRouterContextObject extends Omit<NavigationContextObject, "future"> {
router: Router;

@@ -54,3 +62,3 @@ staticContext?: StaticHandlerContext;

export declare const DataRouterContext: React.Context<DataRouterContextObject | null>;
export declare const DataRouterStateContext: React.Context<import("@remix-run/router").RouterState | null>;
export declare const DataRouterStateContext: React.Context<import("./router/router").RouterState | null>;
export type ViewTransitionContextObject = {

@@ -60,2 +68,3 @@ isTransitioning: false;

isTransitioning: true;
flushSync: boolean;
currentLocation: Location;

@@ -65,2 +74,4 @@ nextLocation: Location;

export declare const ViewTransitionContext: React.Context<ViewTransitionContextObject>;
export type FetchersContextObject = Map<string, any>;
export declare const FetchersContext: React.Context<FetchersContextObject>;
export declare const AwaitContext: React.Context<TrackedPromise | null>;

@@ -72,3 +83,4 @@ export interface NavigateOptions {

relative?: RelativeRoutingType;
unstable_viewTransition?: boolean;
flushSync?: boolean;
viewTransition?: boolean;
}

@@ -95,2 +107,3 @@ /**

static: boolean;
future: {};
}

@@ -97,0 +110,0 @@ export declare const NavigationContext: React.Context<NavigationContextObject>;

import * as React from "react";
import type { Blocker, BlockerFunction, Location, ParamParseKey, Params, Path, PathMatch, PathPattern, RelativeRoutingType, Router as RemixRouter, RevalidationState, To, UIMatch } from "@remix-run/router";
import { Action as NavigationType } from "@remix-run/router";
import type { NavigateOptions, RouteContextObject, RouteMatch, RouteObject } from "./context";
import type { Location, Path, To } from "./router/history";
import { Action as NavigationType } from "./router/history";
import type { Blocker, BlockerFunction, RelativeRoutingType, Router as RemixRouter, RevalidationState } from "./router/router";
import type { ParamParseKey, Params, PathMatch, PathPattern, UIMatch } from "./router/utils";
/**
* Returns the full href for the given "to" value. This is useful for building
* custom links that are also accessible and preserve right-click behavior.
*
* @see https://reactrouter.com/hooks/use-href
Resolves a URL against the current location.
```tsx
import { useHref } from "react-router"
function SomeComponent() {
let href = useHref("some/where");
// "/resolved/some/where"
}
```
@category Hooks
*/

@@ -15,16 +25,30 @@ export declare function useHref(to: To, { relative }?: {

/**
* Returns true if this component is a descendant of a `<Router>`.
* Returns true if this component is a descendant of a Router, useful to ensure
* a component is used within a Router.
*
* @see https://reactrouter.com/hooks/use-in-router-context
* @category Hooks
*/
export declare function useInRouterContext(): boolean;
/**
* Returns the current location object, which represents the current URL in web
* browsers.
*
* Note: If you're using this it may mean you're doing some of your own
* "routing" in your app, and we'd like to know what your use case is. We may
* be able to provide something higher-level to better suit your needs.
*
* @see https://reactrouter.com/hooks/use-location
Returns the current {@link 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 (
// ...
);
}
```
@category Hooks
*/

@@ -36,3 +60,3 @@ export declare function useLocation(): Location;

*
* @see https://reactrouter.com/hooks/use-navigation-type
* @category Hooks
*/

@@ -45,3 +69,3 @@ export declare function useNavigationType(): NavigationType;

*
* @see https://reactrouter.com/hooks/use-match
* @category Hooks
*/

@@ -53,16 +77,32 @@ export declare function useMatch<ParamKey extends ParamParseKey<Path>, Path extends string>(pattern: PathPattern<Path> | Path): PathMatch<ParamKey> | null;

export interface NavigateFunction {
(to: To, options?: NavigateOptions): void;
(delta: number): void;
(to: To, options?: NavigateOptions): void | Promise<void>;
(delta: number): void | Promise<void>;
}
/**
* Returns an imperative method for changing the location. Used by `<Link>`s, but
* may also be used by other elements to change the location.
*
* @see https://reactrouter.com/hooks/use-navigate
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 {@link redirect} in {@link ActionFunction | actions} and {@link LoaderFunction | loaders} than this hook.
@category Hooks
*/
export declare function useNavigate(): NavigateFunction;
/**
* Returns the context (if provided) for the child route at this level of the route
* hierarchy.
* @see https://reactrouter.com/hooks/use-outlet-context
* Returns the parent route {@link OutletProps.context | `<Outlet context>`}.
*
* @category Hooks
*/

@@ -74,10 +114,20 @@ export declare function useOutletContext<Context = unknown>(): Context;

*
* @see https://reactrouter.com/hooks/use-outlet
* @category Hooks
*/
export declare function useOutlet(context?: unknown): React.ReactElement | null;
/**
* Returns an object of key/value pairs of the dynamic params from the current
* URL that were matched by the route path.
*
* @see https://reactrouter.com/hooks/use-params
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` then `params.postId` will be `"123"`.
@category Hooks
*/

@@ -88,5 +138,17 @@ export declare function useParams<ParamsOrKey extends string | Record<string, string | undefined> = string>(): Readonly<[

/**
* Resolves the pathname of the given `to` value against the current location.
*
* @see https://reactrouter.com/hooks/use-resolved-path
Resolves the pathname of the given `to` value against the current location. Similar to {@link useHref}, but returns a {@link 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 // ""
}
```
@category Hooks
*/

@@ -97,11 +159,40 @@ export declare function useResolvedPath(to: To, { relative }?: {

/**
* Returns the element of the route that matched the current location, prepared
* with the correct context to render the remainder of the route tree. Route
* elements in the tree must render an `<Outlet>` to render their child route's
* element.
Hook version of {@link Routes | `<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.
```tsx
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;
}
```
@category Hooks
*/
export declare function useRoutes(routes: RouteObject[], locationArg?: Partial<Location> | string): React.ReactElement | null;
/**
* Internal implementation with accept optional param for RouterProvider usage
*
* @see https://reactrouter.com/hooks/use-routes
* @private
* @category Hooks
*/
export declare function useRoutes(routes: RouteObject[], locationArg?: Partial<Location> | string): React.ReactElement | null;
export declare function useRoutesImpl(routes: RouteObject[], locationArg?: Partial<Location> | string, dataRouterState?: RemixRouter["state"]): React.ReactElement | null;
export declare function useRoutesImpl(routes: RouteObject[], locationArg?: Partial<Location> | string, dataRouterState?: RemixRouter["state"], future?: RemixRouter["future"]): React.ReactElement | null;
type RenderErrorBoundaryProps = React.PropsWithChildren<{

@@ -132,3 +223,3 @@ location: Location;

}
export declare function _renderMatches(matches: RouteMatch[] | null, parentMatches?: RouteMatch[], dataRouterState?: RemixRouter["state"] | null): React.ReactElement | null;
export declare function _renderMatches(matches: RouteMatch[] | null, parentMatches?: RouteMatch[], dataRouterState?: RemixRouter["state"] | null, future?: RemixRouter["future"] | null): React.ReactElement | null;
/**

@@ -139,12 +230,45 @@ * Returns the ID for the nearest contextual route

/**
* Returns the current navigation, defaulting to an "idle" navigation when
* no navigation is in progress
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.
}
```
@category Hooks
*/
export declare function useNavigation(): import("@remix-run/router").Navigation;
export declare function useNavigation(): import("./router/router").Navigation;
/**
* Returns a revalidate function for manually triggering revalidation, as well
* as the current state of any manual revalidations
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...
</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 {@link useFetcher}, {@link Form}, {@link useSubmit} that do this automatically.
@category Hooks
*/
export declare function useRevalidator(): {
revalidate: () => void;
revalidate(): Promise<void>;
state: RevalidationState;

@@ -155,28 +279,131 @@ };

* parent/child routes or the route "handle" property
*
* @category Hooks
*/
export declare function useMatches(): UIMatch[];
/**
* Returns the loader data for the nearest ancestor Route loader
Returns the data from the closest route {@link LoaderFunction | loader} or {@link ClientLoaderFunction | 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>();
// ...
}
```
@category Hooks
*/
export declare function useLoaderData(): unknown;
/**
* Returns the loaderData for the given routeId
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" }})
```
@category Hooks
*/
export declare function useRouteLoaderData(routeId: string): unknown;
/**
* Returns the action data for the nearest ancestor Route action
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 (
<Form method="post">
<input type="text" name="visitorsName" />
{data ? data.message : "Waiting..."}
</Form>
)
}
```
@category Hooks
*/
export declare function useActionData(): unknown;
/**
* Returns the nearest ancestor Route error, which could be a loader/action
* error or a render error. This is intended to be called from your
* ErrorBoundary/errorElement to display a proper error message.
Accesses the error thrown during an {@link ActionFunction | action}, {@link LoaderFunction | loader}, or component render to be used in a route module Error Boundary.
```tsx
export function ErrorBoundary() {
const error = useRouteError();
return <div>{error.message}</div>;
}
```
@category Hooks
*/
export declare function useRouteError(): unknown;
/**
* Returns the happy-path data from the nearest ancestor `<Await />` value
Returns the resolved promise value from the closest {@link Await | `<Await>`}.
```tsx
function SomeDescendant() {
const value = useAsyncValue();
// ...
}
// somewhere in your app
<Await resolve={somePromise}>
<SomeDescendant />
</Await>
```
@category Hooks
*/
export declare function useAsyncValue(): unknown;
/**
* Returns the error from the nearest ancestor `<Await />` value
Returns the rejection value from the closest {@link Await | `<Await>`}.
```tsx
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 />}
/>
```
@category Hooks
*/

@@ -189,4 +416,6 @@ export declare function useAsyncError(): unknown;

* cross-origin navigations.
*
* @category Hooks
*/
export declare function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker;
export {};
/**
* React Router v0.0.0-experimental-4a8a492a
* React Router v0.0.0-experimental-4b431ca46
*

@@ -4,0 +4,0 @@ * Copyright (c) Remix Software Inc.

{
"name": "react-router",
"version": "0.0.0-experimental-4a8a492a",
"version": "0.0.0-experimental-4b431ca46",
"description": "Declarative routing for React",

@@ -23,13 +23,43 @@ "keywords": [

"unpkg": "./dist/umd/react-router.production.min.js",
"module": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/main.js"
},
"./types": {
"types": "./dist/lib/types.d.ts"
},
"./dom": {
"types": "./dist/dom-export.d.ts",
"import": "./dist/dom-export.mjs",
"require": "./dist/main-dom-export.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"@remix-run/router": "0.0.0-experimental-4a8a492a"
"@types/cookie": "^0.6.0",
"@web3-storage/multipart-parser": "^1.0.0",
"cookie": "^0.6.0",
"set-cookie-parser": "^2.6.0",
"source-map": "^0.7.3",
"turbo-stream": "2.4.0",
"react-router": "0.0.0-experimental-4b431ca46"
},
"devDependencies": {
"react": "^18.2.0"
"@types/set-cookie-parser": "^2.4.1",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"peerDependencies": {
"react": ">=16.8"
"react": ">=18",
"react-dom": ">=18"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true
}
},
"files": [

@@ -42,4 +72,4 @@ "dist/",

"engines": {
"node": ">=14.0.0"
"node": ">=18.0.0"
}
}
}
# React Router
The `react-router` package is the heart of [React Router](https://github.com/remix-run/react-router) and provides all
the core functionality for both
[`react-router-dom`](https://github.com/remix-run/react-router/tree/main/packages/react-router-dom)
and
[`react-router-native`](https://github.com/remix-run/react-router/tree/main/packages/react-router-native).
If you're using React Router, you should never `import` anything directly from
the `react-router` package, but you should have everything you need in either
`react-router-dom` or `react-router-native`. Both of those packages re-export
everything from `react-router`.
If you'd like to extend React Router and you know what you're doing, you should
add `react-router` **as a peer dependency, not a regular dependency** in your
package.
The `react-router` package is the heart of [React Router](https://github.com/remix-run/react-router) and provides all the core functionality.

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc