The goal is to ensure that when the drawer is open and on pressing the back button should exit the app instead of closing the drawer. However, the issue is that the BackHandler
is triggering even when the drawer is not open.
const isDrawerOpen = useDrawerStatus()
useEffect(() => {
console.log("Drawer opne status : ", isDrawerOpen)
}, [isDrawerOpen])
const backAction = () => {
console.log("BackAction")
if (true) {
// if (isDrawerOpen === 'open') {
console.log("DRAWER IS OPEN")
BackHandler.exitApp();
return true;
}
return false;
};
useEffect(() => {
const backHandler = BackHandler.addEventListener(
'hardwareBackPress',
backAction
);
return () => backHandler.remove();
}, [isDrawerOpen]);
I also tried using a true
condition, meaning the app should exit on back press regardless of the drawer’s status, but even then, when the drawer is open, pressing the back button still closes the drawer instead of exiting the app.
Arpit Mishra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
In the code you have shared you are always adding the hardware back listener, irrespective of the current isDrawerOpen
value. This means the handler is called even when the drawer is closed.
I suspect you have at least a few options, here are two common patterns:
-
Only add the listener and
backAction
handler whenisDrawerOpen
is true, and remove it when it is closed.const isDrawerOpen = useDrawerStatus(); useEffect(() => { if (isDrawerOpen) { const backAction = () => { BackHandler.exitApp(); return true; }; const backHandler = BackHandler.addEventListener( 'hardwareBackPress', backAction ); return () => { backHandler.remove(); }; } }, [isDrawerOpen]);
-
Only add the listener and
backAction
handler once, and cache theisDrawerOpen
in a React ref that can be referenced in thebackAction
handler.const isDrawerOpen = useDrawerStatus(); const isDrawerOpenRef = useRef(isDrawerOpen); useEffect(() => { isDrawerOpenRef.current = isDrawerOpen; }, [isDrawerOpen]); useEffect(() => { const backAction = () => { if (isDrawerOpenRef.current === 'open') { BackHandler.exitApp(); return true; } return false; }; const backHandler = BackHandler.addEventListener( 'hardwareBackPress', backAction ); return () => { backHandler.remove(); }; }, []);
3