Reputation: 751
I am working on my first React Native app and I want to implement a functionality where whenever the user presses the android back button on the homepage, an Alert pops and asks the user if s/he wants to exit the app. This works until the point where the alert appears but in the end, it exits the app even without pressing the yes button.
Here's my code
BackAndroid.addEventListener('hardwareBackPress', () => {
Alert.alert(
'Quit App?',
'Are you sure you want to exit App?',
[
{text: 'Yes', onPress: () => false},
{text: 'No', onPress: () => true},
],
{ cancelable: true }
)
});
As explained, the alert appears but doesn't wait for the yes or no button to be pressed, it just, exits the app after a ew milleseconds.
Thanks in advance fot the help
Upvotes: 0
Views: 445
Reputation: 5442
You need to return true
in your listener in order to notify the framework you have handled the back button yourself and there is no need for it to do it (by exiting the app).
So just return true
after the alert.
There is a concise description of this in the docs.
Upvotes: 1
Reputation: 11234
I do it like this -
BackAndroid.addEventListener('hardwareBackPress', () => {
Alert.alert(
'Quit App?',
'Are you sure you want to exit App?',
[
{text: 'Yes', onPress: () => BackAndroid.exitApp()},
{text: 'No', onPress: () => {}},
],
);
return true;
});
Upvotes: 2