Blog>
Snippets

Conditional Navigation Blocking

Showcase how to implement conditional navigation blocking in TanStack Router, where the blocking depends on whether the user has interacted with a form, preventing data loss.
import { useBlocker, useNavigationType } from 'react-router-dom';

function usePreventNavigationWhenFormIsDirty(isFormDirty) {
  useBlocker(({ action, retry }) => {
    if (action === 'POP') {
      // Allow back navigation without confirming
      retry();
    } else if (isFormDirty) {
      // Confirm with the user before navigating away
      if (window.confirm('You have unsaved changes. Are you sure you want to leave?')) {
        retry();
      }
    } else {
      // Navigate without confirmation if the form is not dirty
      retry();
    }
  }, [isFormDirty]);
}
This code defines a custom hook 'usePreventNavigationWhenFormIsDirty' that blocks navigation away from the current route using TanStack Router, if the form is dirty (i.e., has unsaved changes). It uses 'useBlocker' to intercept navigation attempts. For back navigation (using the browser's back button), it allows the navigation without confirmation. For other types of navigation, it prompts the user to confirm their intention if the form is dirty. If the user confirms, navigation proceeds; otherwise, it is blocked. This helps prevent data loss by warning users about unsaved changes.