Avijeet Dey
Avijeet Dey

Reputation: 31

How to stop browser back button using react js hooks and history api?

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

Answers (3)

Sylvain L
Sylvain L

Reputation: 216

This code works fine for me :

useEffect(() => {
    return () => {
        if (history.action === 'POP') {
            history.go(1);
        }
    };
}, [history]);

Upvotes: 1

axtck
axtck

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

Abdulhakim Zeinu
Abdulhakim Zeinu

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

Related Questions