diff --git a/docs/how-to/navigation-blocking.md b/docs/how-to/navigation-blocking.md new file mode 100644 index 0000000000..72545c0251 --- /dev/null +++ b/docs/how-to/navigation-blocking.md @@ -0,0 +1,232 @@ +--- +title: Navigation Blocking +--- + +# Navigation Blocking + +[MODES: framework, data] + +## Overview + +When users are in the middle of a workflow, like filling out an important form, you may want to prevent them from navigating away from the page. + +This example will show: + +- Setting up a route with a form and action called with a fetcher +- Blocking navigation when the form is dirty +- Showing a confirmation when the user tries to leave the page + +## 1. Set up a route with a form + +Add a route with the form, we'll use a "contact" route for this example: + +```ts filename=routes.ts +import { + type RouteConfig, + index, + route, +} from "@react-router/dev/routes"; + +export default [ + index("routes/home.tsx"), + route("contact", "routes/contact.tsx"), +] satisfies RouteConfig; +``` + +Add the form to the contact route module: + +```tsx filename=routes/contact.tsx +import { useFetcher } from "react-router"; +import type { Route } from "./+types/contact"; + +export async function action({ + request, +}: Route.ActionArgs) { + let formData = await request.formData(); + let email = formData.get("email"); + let message = formData.get("message"); + console.log(email, message); + return { ok: true }; +} + +export default function Contact() { + let fetcher = useFetcher(); + + return ( + +

+ +

+

+