How do I exit/shut down a React Native app?

ReactjsNativeReact Native

Reactjs Problem Overview


If my React Native app fails to connect to its backend, I show an Alert with an OK button. If this happens, there's no point in the app continuing to run, so I'd like to shut it down when the button is clicked. How do I do this?

I suspect the key is in AppRegistry but the docs are a bit scant.

Reactjs Solutions


Solution 1 - Reactjs

For Android, Use BackHandler to exit the App:

import React, { BackHandler } from 'react-native';

BackHandler.exitApp();

Solution 2 - Reactjs

I am answering the question too late, but i thought the way i have chosen might help someone, so I am answering this question.

componentWillMount() {
   BackHandler.addEventListener('hardwareBackPress', this.backPressed);
}

componentWillUnmount() {
   BackHandler.removeEventListener('hardwareBackPress', this.backPressed);
}

backPressed = () => {
  Alert.alert(
    'Exit App',
    'Do you want to exit?',
    [
      {text: 'No', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
      {text: 'Yes', onPress: () => BackHandler.exitApp()},
    ],
    { cancelable: false });
    return true;
}

Solution 3 - Reactjs

There's no react-native specific way to do this today. You'd have to accomplish this from the native side of things.

Further, are you developing for iOS? Apple has stated that apps should not close themselves.

Solution 4 - Reactjs

Write a native module that performs the following actions when called:

IOS:

exit(9);

ANDROID:

((YourApplication) self.getApplicationContext()).kill();

...EDIT...

Or just use the one I created: https://www.npmjs.com/package/react-native-exit-app

Solution 5 - Reactjs

This is how I've achieved it:

  componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
  }
  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
  }
  handleBackButtonClick() {
    BackHandler.exitApp();
    return true;
  }

Solution 6 - Reactjs

This npm module helped me with the same issue - react-native-exit-app

import RNExitApp from 'react-native-exit-app';
...
RNExitApp.exitApp();
...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNolanView Question on Stackoverflow
Solution 1 - ReactjsherbertDView Answer on Stackoverflow
Solution 2 - ReactjsFazeel QureshiView Answer on Stackoverflow
Solution 3 - ReactjsAdam TerlsonView Answer on Stackoverflow
Solution 4 - ReactjsWiRaView Answer on Stackoverflow
Solution 5 - ReactjsarledView Answer on Stackoverflow
Solution 6 - ReactjsRomanSorinView Answer on Stackoverflow