Listen To Back Button In Mobile Browser And E.preventdefault() Then Use Our Separate Function In React Function
I am working on a react web app add want to preventDefault back button to my function in react function for exact code use check -https://github.com/rishabhjainfinal/react-expence-
Solution 1:
I still don't see where you try to prevent any back navigation, but you can use history.block
from the router context. When a "POP" action is initiated you can run your custom logic to allow or block the route transition from occurring.
The following is an example usage:
const history = useHistory();
useEffect(() => {
const unblock = history.block((location, action) => {
if (action === "POP") {
// Return true to allow transition, false to blockreturnwindow.confirm("Navigate Back?");
}
});
return() => {
unblock();
};
}, []);
Full example code:
constTestComponent = () => {
const history = useHistory();
React.useEffect(() => {
const unblock = history.block((location, action) => {
if (action === "POP") {
returnwindow.confirm("Navigate Back?");
}
});
return() => {
unblock();
};
}, []);
return (
<div><h3>Test Page</h3><div><p>Try navigating away</p></div></div>
);
};
functionApp() {
return (
<divclassName="App"><h1>Hello CodeSandbox</h1><h2>Start editing to see some magic happen!</h2><Router><ul><li><Linkto="/">Home</Link></li><li><Linkto="/test">Test</Link></li><li><Linkto="/other">Other</Link></li></ul><Switch><Routepath="/test"><TestComponent /></Route><Routepath="/other"><div><h3>Some Other Page</h3><div><p>This is some other page</p></div></div></Route><Route><div><h3>Home Page</h3><div><p>This is the home page</p></div></div></Route></Switch></Router></div>
);
}
Using window.beforeunload
Here is a fairly trivial example for how to use window.beforeunload
.
React.useEffect(() => {
constcallback = (e) => {
if (blockingCondition) {
e.preventDefault();
e.returnValue = "";
}
};
window.addEventListener("beforeunload", callback);
return() =>window.removeEventListener("beforeunload", callback);
}, [blockingCondition]);
Post a Comment for "Listen To Back Button In Mobile Browser And E.preventdefault() Then Use Our Separate Function In React Function"