Hello Friends,

Welcome To Infinitbility!

This article will you to exit your react native application programmatically when you use react-navigation for managing routes you get the inbuild feature back press exit application from the first route but many times we want to close the application when we want.

React native not provide any exit functionality for react native ios application but we have BackHandler for android, and today you get an example of BackHandler, how to use BackHandler in react native application.

Let’s start today article How to close react native app programmatically

React Native provides the BackHandler component to handle exit functionality in android.

when you call BackHandler.exitApp(); app will close but it will remain in android’s recent tab.

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

BackHandler.exitApp();

Here, I will share React Native BackHandler example to use when the user presses the back button.

when you want to exit the application when the user clicks on the back button you have to use hardwareBackPress EventListener, let’s understand with an example.

ReactNativeBackHandler.js

import React, { Component } from "react";
import { Text, View, StyleSheet, BackHandler, Alert } from "react-native";

class App extends Component {
  backAction = () => {
    Alert.alert("Hold on!", "Are you sure you want to go back?", [
      {
        text: "Cancel",
        onPress: () => null,
        style: "cancel"
      },
      { text: "YES", onPress: () => BackHandler.exitApp() }
    ]);
    return true;
  };

  componentDidMount() {
    this.backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      this.backAction
    );
  }

  componentWillUnmount() {
    this.backHandler.remove();
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.text}>Click Back button!</Text>
      </View>
    );
  }
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center"
  },
  text: {
    fontSize: 18,
    fontWeight: "bold"
  }
});

export default App;

Thanks for reading…