how to exit react native app when clicking a button?

23,069

Solution 1

import BackHandler from 'react-native';
// Note: work only on Android
    BackHandler.exitApp();

Solution 2

For iOS, you can use the following library: https://github.com/wumke/react-native-exit-app. It uses native library to exit the app programmatically. You can exit the app using:

RNExitApp.exitApp()

For android, you can use BackAndroid from https://facebook.github.io/react-native/docs/backandroid.html

BackAndroid.exitApp()

Solution 3

Apple would reject your iOS app if you exit the app on button click. You could just show an alert without a button. User won't be able to dismiss the alert and enter the app rendering it useless.

Solution 4

BackAndroid should be able to help you. Use Alert callback to use BackHandler

var {
  Alert,
  BackHandler,
} = ReactNative;



Alert.alert(
            'Alert Title',
            alertMessage,
            [
              {text: 'OK', onPress: () => BackHandler.exitApp()},
            ]
);

Solution 5

<Text style = {something}
        onPress ={
        ()=>{
        console.log('clicked');
        return BackHandler.exitApp();
        }
        }>Exit</Text>
Share:
23,069
Nahum Fabian
Author by

Nahum Fabian

Updated on July 09, 2022

Comments

  • Nahum Fabian
    Nahum Fabian almost 2 years

    I am devloping a mobile app using react native and i want to exit the app after clicking a button.

    My scenario is that if the user has not verified his/her email after certains days i will prompt the user an Alert Dialog every the time the app is opened blocking the app usage until the user email is verified.

    So after the users click OK, how do I exit the app programmatically?

  • Irfan Ayaz
    Irfan Ayaz over 7 years
    Should this be used with platform check? BackAndroid wont work for iOS!
  • Nahum Fabian
    Nahum Fabian over 7 years
    your solution makes sense but the issue is that Alerts cannot be displayed without buttons in react native. By default a button is included and there is no way to hide it base on what i have read so far. do you know how to show an alert without buttons?
  • Badacadabra
    Badacadabra almost 7 years
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
  • Azmeer
    Azmeer over 6 years
    BackAndroid is deprecated. Use BackHandler instead.
  • Anurag Shrivastava
    Anurag Shrivastava almost 6 years
    BackHandler.exitApp() is exit only current screen. how to exit from application and clear the stack.
  • Moein Hosseini
    Moein Hosseini about 5 years
    BackHandler.exitApp() work both for android and ios.
  • markuscosinus
    markuscosinus almost 5 years
    @Moein No, it doesn't
  • Saravanabalagi Ramachandran
    Saravanabalagi Ramachandran over 4 years
    @NirLevy The author updated the licence to a more permissive MIT licence :)