Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Android BackHandler Exit App

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?

like image 606
Abdul-Elah JS Avatar asked Jul 14 '26 08:07

Abdul-Elah JS


1 Answers

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.

like image 108
Dror Bar Avatar answered Jul 15 '26 21:07

Dror Bar