FormLeaveGuard

Ask before leaving a page with unsaved changes.

Installation
bunx --bun shadcn@latest add @fieldkit/form-leave-guard

Needs the @fieldkit registry. Add it once

Usage
Terminal
import { FormLeaveGuard } from "@/components/form/form-leave-guard"
<Form mode="edit" ...>  ...  <FormLeaveGuard /></Form>
// Source"use client"
import { useBlocker } from "@tanstack/react-router"
import { useFormChanges } from "@/components/form/form"
export function FormLeaveGuard({  message = "Leave without saving? Your changes will be lost.",}: {  message?: string}) {  const { hasChanges, isSubmitting } = useFormChanges()  const shouldGuard = hasChanges && !isSubmitting
  useBlocker({    shouldBlockFn: () => shouldGuard && !window.confirm(message),    enableBeforeUnload: shouldGuard,  })
  return null}
Notes
  • Blocks router navigation and closing the tab while the form has changes.
  • Stops guarding while the form submits.

Search docs

Find a component, input or example