In my react app I have a popup in one of the page. Now when the popup is open and the user presses browser's back button then user is taken to the previous page, instead I want to simply close the popup.
I have followed a lot of solutions related to this but none seems to work. The below code allows me to close the popup on back but what it does is push an extra url in history of the page in which popup is present. Hence once popup is closed I need to press back twice to actually get to previous page. This gives a bad user experience hence I wont want to add it to my app.
const myPopState = (event) => {
window.history.go(1);
closeModal();
};
useEffect(() => {
window.history.pushState(null, null, location.href);
window.addEventListener("popstate", myPopState);
return () => window.removeEventListener("popstate", myPopState);
}, []);
PS: I dont want to have a separate route for the popup screen. There is a similar question asked already but I am not willing to put in a unique route for popup so asking this.