I'm having trouble in preventing the path from redirecting whenever I click the browser's back button then click the "Cancel" button in the confirmation box.
componentDidMount() {
window.addEventListener('popstate', this.quit);
}
quit = () => {
if(confirm('Quit?')) {
location.assign('/'); // Refreshes the browser then redirects to the homepage
history.pushState(null, null, null); // Clears the previous history
} else {
// What to do if the user clicks "Cancel"?
}
}
I tried return false
but it's still redirecting the app to the homepage (but without refreshing the page). I've tried other solutions like location.pathname = '/currentPathname'
and location.replace('/currentPathname')
, but since these reload the browser, it displays Cannot get /currentPathname
because React Router doesn't need to reload. The <Prompt />
component didn't solve the problem as well because it doesn't have a function prop where I can execute the code above.