Reputation: 31
I'm trying to disable back button after successful login into the application but couldn't make it. I'm using react router dom 5.2.0 for routing. Currently, I'm redirecting to login page if someone clicks to browser back button but I need to block the back button.
useEffect(() => {
return () => {
if (history.action === "POP") {
history.replace('/login');
}
};
}, [history]);
Upvotes: 3
Views: 10116
Reputation: 216
This code works fine for me :
useEffect(() => {
return () => {
if (history.action === 'POP') {
history.go(1);
}
};
}, [history]);
Upvotes: 1
Reputation: 3965
There is no way to fully disable the browsers back button, you can only prevent it from going back like you are doing.
When you are doing this, don't forget to listen for events on history
, try this out:
useEffect(() => {
return history.listen(() => { // listen
if (history.action === "POP") {
history.replace("/login");
}
});
}, [history]);
Upvotes: 1
Reputation: 3829
Here is how you can stop the browser's back button
history.pushState(null, null, location.href);
window.onpopstate = function(event) {
history.go(1);
};
Upvotes: 1