I want to show a prompt alert when user wants to close or refresh the page in a specific component in react js and based on confirming the refresh or the closing window do some different logic . here is my code that an AI recommond but it didnt worked for me ! how to fix that ?
function MyComponent() {
useEffect(() => {
const handleBeforeUnload = (event) => {
event.preventDefault();
const confirmationMessage = "Are you sure you want to leave this page?";
event.returnValue = confirmationMessage;
if (window.confirm(confirmationMessage)) {
// Logic to execute when the user clicks "OK" (Yes)
console.log("User clicked Yes");
// Perform your desired logic here for "Yes" response
} else {
// Logic to execute when the user clicks "Cancel" (No)
console.log("User clicked No");
// Perform your desired logic here for "No" response
}
};
window.addEventListener("beforeunload", handleBeforeUnload);
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
};
}, []);
Try this :