简体   繁体   中英

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.

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);
  };
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM