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]);
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]);
Share
Improve this question
edited Nov 7, 2021 at 19:02
Ahmet Emre Kilinc
6,98319 gold badges36 silver badges47 bronze badges
asked Mar 12, 2021 at 8:06
Avijeet DeyAvijeet Dey
311 gold badge1 silver badge2 bronze badges
1
- Did you check out my answer? Consider giving some feedback, greetings! – axtck Commented Mar 16, 2021 at 16:24
3 Answers
Reset to default 1Here is how you can stop the browser's back button
history.pushState(null, null, location.href);
window.onpopstate = function(event) {
history.go(1);
};
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]);
This code works fine for me :
useEffect(() => {
return () => {
if (history.action === 'POP') {
history.go(1);
}
};
}, [history]);