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?
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 ?
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.
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]); //... };
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With