I want to implement the BackHandler to run on one component and keep the default behavior of the hardware back button 'go to the previous screen' in the rest of my app, I have a component named 'cases.js' I want to exit the app if the user clicked the back button while this component is in the screen and to navigate back if the user is on any other component, the cases screen lays over the Login screen.
Here is what I've tried in 'cases.js' file:
componentDidMount = async () => {
await BackHandler.addEventListener('hardwareBackPress', this._closeApp())
}
componentWillUnmount = async () => {
await BackHandler.removeEventListener('hardwareBackPress', this_closeApp());
}
_closeApp = async () => {
BackHandler.exitApp();
}
but it keeps closing the app immediately.
How may I achieve that?
Since I can't add comments yet - adding to Mahdi Bashirpour's answer, which is correct:
componentWillMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
}
handleBackButton = () => {
//add your code
return true;
};
This code will work, but as you noticed, once you add EventListener on Login screen it will affect all other screens deeper in the stack that do not overwrite BackHandler EventListener.
The best way to solve this is to add another condition that checks that you are in Login screen:
handleBackButton = () => {
if (screen == 'Login') {
BackHandler.exitApp();
return true;
}
};
How to check which screen you are on? Assuming you are using React-Navigation take a look here. If you are having problems tracking the current screen I suggest opening a new thread.
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