Implementing Navigation Blocking with React Router:
React Router provides the useBlocker hook, which allows us to block navigation programmatically.
We can use it to conditionally block navigation based on specific criteria, such as unsaved form data or user authentication status.
Example: Blocking Navigation with Unsaved Changes:
import React, { useState, useEffect } from 'react';
import { useBlocker } from 'react-router-dom';
const FormComponent = () => {
const [formData, setFormData] = useState({});
const [draftSaved, setDraftSaved] = useState(false);
const blocker = useBlocker(({ currentLocation, nextLocation }) =>
draftSaved && currentLocation.pathname !== nextLocation.pathname
);
return (<>
{blocker.state === "blocked" ? (
<div>
<p>Are you sure you want to leave?</p>
<button onClick={() => blocker.proceed()}>Proceed</button>
<br />
<button onClick={() => blocker.reset()}>Cancel</button>
</div>
): null}
<>)
};
Top comments (0)