I have to show an alert on the browser back event on React js. I have tried using the addEventListener
but I'm not sure where to place the code in the React page. Should I place in any life-cycle hooks or in the render? I'm not sure. Please help me out.
The popstate event is only triggered by performing a browser action, such as clicking on the back button (or calling history. back() in JavaScript), when navigating between two history entries for the same document.
if you use react hooks you can use useEffect hooks to do it in following step
import React, { useState, useEffect } from "react";
const [finishStatus, setfinishStatus] = useState(false);
const onBackButtonEvent = (e) => {
e.preventDefault();
if (!finishStatus) {
if (window.confirm("Do you want to go back ?")) {
setfinishStatus(true)
// your logic
props.history.push("/");
} else {
window.history.pushState(null, null, window.location.pathname);
setfinishStatus(false)
}
}
}
useEffect(() => {
window.history.pushState(null, null, window.location.pathname);
window.addEventListener('popstate', onBackButtonEvent);
return () => {
window.removeEventListener('popstate', onBackButtonEvent);
};
}, []);
I found this solution and it is working fine for me.
constructor(props) {
super(props);
this.state = {
onClickBackButton: false
};
}
componentDidMount() {
window.history.pushState(null, null, window.location.pathname);
window.addEventListener('popstate', this.onClickBackButton);
}
onBackButtonEvent = (e) => {
e.preventDefault();
if (!this.onClickBackButton) {
if (window.confirm("Do you want to go back without submitting details?")) {
this.onClickBackButton= true;
// your custom logic to page transition,like react-router-dom
history.push()
} else {
window.history.pushState(null, null, window.location.pathname);
this.onClickBackButton= false;
}
}
}
componentWillUnmount = () => {
window.removeEventListener('popstate', this.onClickBackButton);
}
Ref
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