Saturday, April 20, 2019

Handling Android Back Button Press in React Native

In this tutorial we are going to discuss how to make the App Quit When Hardware Back Button is pressed in React Native application. Unlike in iOS devices, Android devices have hardware back button which is used to navigate through previous screens. Sometimes, you may need to make the app quit when the back button is pressed. Hardware back button is a most important part of every android mobile phone. Back button gives us the functionality to going back in previous activity without any customization in application. If we would on the main home page activity screen then by default pressing back button would exit us from the app. In react native we can modify the android’s hardware back button behavior and override it according to our requirement
Handling Android Back Button Press in React Native

BackHandler
is the api used in React Native to modify the behavior of Android hardware back button. BackHandler.exitApp() function is used to exit the app. You have to add event listener to listen to the actions of back button using BackHandler.addEventListener function. The listener should be removed in componentWillUnmount using BackHandler.removeEventListener function.

React Native Override Android Hardware Back Button Behavior

In this example we are going to implement android hardware back button press event listener in react native application. Go through the below steps that help you to build more understanding on this.



Step 1: First create the new reactive project.

Step 2: Open App.js File in your favorite code editor and erase all code and follow this tutorial.

Step 3: Through react , react-native packages import all required components.
import React, { Component } from 'react';
import { Platform, StyleSheet, View, Text, Alert, BackHandler  } from 'react-native';

Step 4 Create componentWillMount() function and adding event listener with BackHandler component. Using this we would define our function here which we would call on back button press.
componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', this.onBackPress);
  }

Step 5 Create componentWillUnmount() function and again remove event listener with BackHandler component. It will remove the event listener on back button press event.
componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.onBackPress);
  }

Step 6: Create onBackPress function inside the App component and use the custom Alert message dialog box. This Alert message dialog box display Yes and No message, when user clicks on android hardware back button. When user select the Yes and No message from the Alert dialog box, then following thing will happen.
1. Yes : It would call the default BackHandler.exitApp() function.
2. No : Nothing will happen and app remains in same state.
At last we would return true in function to enable back button override behavior.
onBackPress = () => {
 
    //Code to display alert message when use click on android device back button.
    Alert.alert(
      ' Exit From App ',
      ' Do you want to exit From App ?',
      [
        { text: 'Yes', onPress: () => BackHandler.exitApp() },
        { text: 'No', onPress: () => console.log('NO Pressed') }
      ],
      { cancelable: false },
    );
 
    // Return true to enable back button over ride.
    return true;
  }

Step 7: Open App.js component and and Implement render method. Apply the below code inside the render block of your App component.
render() {

    return (
      <View style={styles.container}>
        <Text style={styles.headerText}>Press Hardware back button and see the alert message {"\n"}</Text>        
      </View>
    );
  }

Step 8: Apply the below style sheet design. 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  headerText: {
    fontSize: 20,
    textAlign: "center",
    margin: 10,
    fontWeight: "bold"
  },

});


Complete Source Code for App.js 

Lets see the complete source code that helps to display alert message when user clicks on android hardware back button in react native application. 

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


export default class App extends Component {
  

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

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

  onBackPress = () => {
 
    //Code to display alert message when use click on android device back button.
    Alert.alert(
      ' Exit From App ',
      ' Do you want to exit From App ?',
      [
        { text: 'Yes', onPress: () => BackHandler.exitApp() },
        { text: 'No', onPress: () => console.log('NO Pressed') }
      ],
      { cancelable: false },
    );
 
    // Return true to enable back button over ride.
    return true;
  }


  render() {

    return (
      <View style={styles.container}>
        <Text style={styles.headerText}>Press Hardware back button and see the alert message {"\n"}</Text>        
      </View>
    );
  }
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  headerText: {
    fontSize: 20,
    textAlign: "center",
    margin: 10,
    fontWeight: "bold"
  },

});

Screenshot :

Handling Android Back Button Press in React Native


Handling Android Back Button Press in React Native

This is all about Handling Android Back Button Press in React Native. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


No comments:

Post a Comment