Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Back Button from browser in React

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.

like image 953
Prateek Thapa Avatar asked Feb 06 '26 12:02

Prateek Thapa


2 Answers

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);
  };
}
like image 91
rrr Avatar answered Feb 08 '26 02:02

rrr


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.

like image 31
Anton Pegov Avatar answered Feb 08 '26 01:02

Anton Pegov



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!