2

After logging into my Dashboard component, I don`t want the user to go back to my login page by using back button in the browser.

I`m not using Redux but only React.

Prateek Thapa
  • 4,829
  • 1
  • 9
  • 23

2 Answers2

3

I think this will help, if the user is logged in then stay on the same page.

if(loggedIn) {
  history.pushState(null, null, location.href);
  window.onpopstate = function(event) {
  history.go(1);
  };
}
RRR
  • 3,509
  • 4
  • 29
  • 38
  • 1
    componentDidMount() { const { loggedIn } = this.state; const { history, location } = window; if (loggedIn) { history.pushState(null, null, location.href); window.onpopstate = event => { event.preventDefault(); history.go(1); }; } } – Prateek Thapa Aug 11 '17 at 05:47
  • for me it goes back then comes back to current page – Sujit.Warrier Jan 27 '21 at 12:33
0

I prefere using my custom hook to intercept browser's back navigation:

import { useEffect, useRef } from "react";

// Intercepts browser's Navigate Back event
export const useNavigateBack = (callback: Function): void => {
  const isInitialMount = useRef(true);
  
  useEffect(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false;
      
      window.addEventListener('popstate', function(event) {
        window.history.pushState(null, '', document.URL);
        event.stopImmediatePropagation();
        callback();
      }, false);
    } else {
       // In my special case this fix was needeed:
       // window.history.pushState(null, '', document.URL);
    }
  }, [callback]);
}

And now I can call use useNavigateBack([my custom back navigation handler]) inside my component.

Anton Pegov
  • 1,413
  • 2
  • 20
  • 33