Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent user from going back in react-router-dom?

I'm using react-router-dom for routing in my reactjs app. And i want to prevent user from going back after login i.e i don't want to user go back again on login screen when he hit back button on browser after login.

like image 706
Vishal Goel Avatar asked Oct 23 '25 10:10

Vishal Goel


2 Answers

Using componentDidUpdate method of React page lifecycle, you can handled or disabled go back functionality in browser. basically componentDidUpdate method will call automatocally when component got updated. so once your component is updated you can prevent to go back as below.

componentDidUpdate() {
  window.history.pushState(null, document.title, window.location.href);
  window.addEventListener('popstate', function(event) {
    window.history.pushState(null, document.title, window.location.href);
  });
}

This will prevent to user go back and uses the current page as a refernce for history object . so incase of user even click on back button of browser, they can not go backword in the last page.

like image 66
ankitkanojia Avatar answered Oct 26 '25 01:10

ankitkanojia


You can checkout this codesandbox example may be that will help you or someone who is looking for the same.In this we can prevent the user to go back to previous page,For more detail checkout this medium article. here is small part of the code

componentDidMount() {
 const { history } = this.props;
  window.addEventListener("popstate", () => {
  history.go(1);
});
}

for full working example click on this link.

like image 29
Zaif Warm Avatar answered Oct 26 '25 00:10

Zaif Warm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!