Say you want to warn users before closing the page, but only when a specific component is loaded, here’s what to do:
import React, { useEffect } from "react";
const WrapperWithBeforeUnload = ({
msg = 'Please reconsider before closing this page',
children
}) => {
const beforeUnloadHandler = (e) => {
e.preventDefault();
return e.returnValue = msg;
}
useEffect(() => {
window.addEventListener("beforeunload", beforeUnloadHandler);
return () => window.removeEventListener("beforeunload", beforeUnloadHandler);
}, []);
return children || <React.Fragment />;
}