DEV Community

Sarwar Hossain
Sarwar Hossain

Posted on • Updated on

Navigation Blocking in Navigation Blocking in React in Other Locations: Preventing Unsaved Changes

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:

Image description



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}
<>)
};



Enter fullscreen mode Exit fullscreen mode

Top comments (0)