Detects when user clicks on the back button.
npm install detect-browser-back-navigation
npm install detect-browser-back-navigation --save
`
`
yarn add detect-browser-back-navigation
`
Usage
Just call the default exported function with a callback on the first argument and the callback will fired whe the user clicks on the back button.
`js
import detectBackButton from 'detect-browser-back-navigation';
const unsub = detectBackButton(() => {
console.log('BACK BUTTON PRESSED!');
});
`
Note: You must properly unsubscribe when the modal is closed, to remove event listeners and avoid fire the callback multiple times leading in bugs.
See below an example of how to create a modal in React:
`jsx
import detectBackButton from 'detect-browser-back-navigation';
export default function Modal(props) {
const [show, setShow] = useState(false);
useEffect(() => {
if (show) {
const unsub = detectBackButton(() => close());
return unsub;
}
}, [show]);
function open() {
setShow(true);
}
function close() {
setShow(false);
}
if (!show) return null;
return (...);
}
``