Ravi Kant Mishra
Ravi Kant Mishra

Reputation: 768

Prevent browser back button for a specific page only in react

I am trying to prevent browser back button for a specific page only in react redux project. Lets say I have four pages.

http://localhost:3000/abc/#/page1,

http://localhost:3000/abc/#/page2,

http://localhost:3000/abc/#/page3

and http://localhost:3000/abc/#/page4

etc

For all the pages user can go back and forth except page4. Once user has visited page3 and clicked the next button he can not go back.

I have tried multiple options but none of them is working as expected. Below code is working as per my expectation but its blocking browser back for all the pages.

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

Upvotes: 6

Views: 13234

Answers (2)

Mahadi Hassan
Mahadi Hassan

Reputation: 1016

You can do it using react-router-dom

import { useHistory } from "react-router-dom";

let history = useHistory();
history.replace("/login");

If you want to do it in logout function :

const logoutClicked = () => {
    localStorage.clear(); //if you want to clear localstorage data
    history.replace("/login"); //redirect to login
  };

If react-router-dom is version >6, use useNavigate instead of useHistory:

import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
navigate("/login");

Upvotes: 2

Herat Patel
Herat Patel

Reputation: 798

If you are using react-router or react-router-dom then you can conditionally disable back button for browser based on current route path.

You can use withRouter Higher order component from react-router or react-router-dom, if your component is not a direct route component.

componentDidMount() {
   const { match } = this.props;
   if(match.url === "/abc/#/page4"){
     window.history.pushState(null, document.title, window.location.href);
     window.addEventListener('popstate', function (event){
        window.history.pushState(null, document.title,  window.location.href);
     });
   }      
}

Upvotes: 5

Related Questions