Cannot get BackHandler.removeEventListener to work. Can anyone please guide as of how to use it?
componentDidMount() {
this.backHandler = BackHandler.addEventListener('hardwareBackPress', handler);
}
componentWillUnmount() {
this.backHandler.remove();
}
An update on how to do it with hooks - I finally made it working by keeping the function we are passing in BackHandler.addEventListener inside useEffect only and with it by using isFocused method of navigation. Any change in the following code breaks it -
useEffect(() => {
const backAction = () => {
if (navigation.isFocused()) {
Alert.alert("Hold on!", "Are you sure you want to exit the app?", [
{
text: "Cancel",
onPress: () => null,
style: "cancel"
},
{ text: "YES", onPress: () => BackHandler.exitApp() }
]);
return true;
}
};
const backHandler = BackHandler.addEventListener("hardwareBackPress", backAction);
return () => backHandler.remove();
}, [])
This is my second answer, if it helps please mark this as useful.
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