Navigation Blocking
Learn how to block navigation and prompt users before they leave a page with unsaved changes.Overview
React Router provides theuseBlocker hook to prevent navigation and prompt users when they attempt to leave a page. This is useful for forms with unsaved changes, preventing accidental data loss.
Basic Navigation Blocking
Block navigation when there are unsaved changes:Blocker States
The blocker has three possible states:Conditional Blocking
Block navigation only under specific conditions:Blocker with Form State
Reset blocker after successful form submission:Custom Confirmation Dialog
Create a reusable confirmation dialog:Multiple Blockers
Handle multiple blocking conditions:Browser Confirmation
Combine with browser’s native confirmation for external navigation:Blocking with Route Parameters
Block navigation based on route changes:Keyboard Shortcuts
Handle keyboard shortcuts while navigation is blocked:Auto-save Integration
Combine blocking with auto-save:Best Practices
- Only block when necessary - Don’t block if form is empty or unchanged
- Allow same-route navigation - Don’t block form submissions to the same route
- Clear state on success - Reset blocking after successful submission
- Provide clear messaging - Tell users why they’re being blocked
- Handle browser navigation - Use
beforeunloadfor external navigation - Make dialogs accessible - Use proper ARIA labels and keyboard navigation
- Consider auto-save - Reduce the need for blocking entirely
- Test thoroughly - Ensure blocking works across all navigation methods