I am using React. I want to warn the user when the user clicks on the back button.
What I had done was
handleWindowClose = (ev) => {
ev.preventDefault();
return ev.returnValue = 'Leaving this page will loose data';
}
componentDidMount = () => {
window.addEventListener('beforeunload',this.handleWindowClose);
}
componentWillUnmount = () => {
window.removeEventListener('beforeunload',this.handleWindowClose);
}
However, this does not work with a back button click. So I tried doing this:
handleWindowClose = (ev) => {
ev.preventDefault();
return ev.returnValue = 'Leaving this page will loose data';
}
onBackButtonEvent = (e) => {
e.preventDefault();
if (confirm("Do you want to loose this data")) {
window.history.go(0);
}
else {
window.history.forward();
}
}
componentDidMount = () => {
window.addEventListener('beforeunload',this.handleWindowClose);
window.addEventListener('popstate',this.onBackButtonEvent);
}
componentWillUnmount = () => {
window.removeEventListener('beforeunload',this.handleWindowClose);
window.removeEventListener('popstate',this.onBackButtonEvent);
}
I am not using react-router. Is there a better way to do this using only React? Also I want the window to stay on that page without using history.forward() as I will lose the window state.
Intercept or Handle the Browser's Back Button in React Router. We can listen to back button actions by running the setRouteLeaveHook event for back button actions. } export default withRouter(App);
Usage: import { useNavigate } from 'react-router-dom'; import { useBackListener } from '../path/to/useBackListener'; ... const navigate = useNavigate(); useBackListener(({ location }) => console. log("Navigated Back", { location }); navigate("/", { replace: true }); );
To go back to the previous page with React Router v5, we can use the useHistory hook. We have the Foo and Bar components which calls the useHistory hook. In both components, we set the history. goBack method as the value of the onClick prop.
I am having the below problems when handling the back button in React:
To solve problem 1, I did the following code:
componentDidMount() {
window.history.pushState(null, null, window.location.pathname);
window.addEventListener('popstate', this.onBackButtonEvent);
}
To solve problem 2, I did the below code:
onBackButtonEvent = (e) => {
e.preventDefault();
if (!this.isBackButtonClicked) {
if (window.confirm("Do you want to save your changes")) {
this.isBackButtonClicked = true;
// Your custom logic to page transition, like react-router-dom history.push()
}
else {
window.history.pushState(null, null, window.location.pathname);
this.isBackButtonClicked = false;
}
}
}
Don't forget to add this.isBackButtonClicked = false; in the constructor and unscubscribe the events.
componentWillUnmount = () => {
window.removeEventListener('popstate', this.onBackButtonEvent);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With