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.
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.