Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent route change using react-router

There's a certain page in my React app that I would like to prevent the user from leaving if the form is dirty.

In my react-routes, I am using the onLeave prop like this:

<Route path="dependent" component={DependentDetails} onLeave={checkForm}/> 

And my onLeave is:

const checkForm = (nextState, replace, cb) => {   if (form.IsDirty) {     console.log('Leaving so soon?');     // I would like to stay on the same page somehow...   } }; 

Is there a way to prevent the new route from firing and keep the user on the same page?

like image 526
Mark Kadlec Avatar asked May 10 '16 17:05

Mark Kadlec


People also ask

How do I restrict routes in React router?

To restrict access to routes in React Router, we set the render prop to a function that renders the component we want according to the condition we're checking. import { Route, Redirect } from "react-router"; <Route exact path="/" render={() => (loggedIn ?

How do I use React router without changing URL?

To use React Router without changing the URL, we can use the MemoryRouter component. to import the MemoryRouter component and then wrap it around App to let us navigate with React Router without changing URLs.

How does my router detect route change React?

To detect route change with React Router, we can use the useLocation hook. import { useEffect } from "react"; import { useLocation } from "react-router-dom"; const SomeComponent = () => { const location = useLocation(); useEffect(() => { console. log("Location changed"); }, [location]); //... };


Video Answer


1 Answers

It is too late but according to the React Router Documentation you can use preventing transition with helping of <prompt> component.

  <Prompt       when={isBlocking}       message={location =>         `Are you sure you want to go to ${location.pathname}`       }     /> 

if isBlocking equal to true it shows a message. for more information you can read the documentation.

like image 199
MBehtemam Avatar answered Oct 06 '22 03:10

MBehtemam