The Android Back Button

Image 1: sample hardware Android Back Button

The Android Back Button (ABB from now on) is a cool functionality of Android phones and Android users are very used to it. iPhone does not have something like it, but if you are developing a React Native app for Android, you need to make sure you add the functionality and make it work “as expected”.

ABB’s expected behavior conveys over the following behaviors:

1. navigate to the previous view

Image 2: Clicking the Android Back Button in Shop view to return back to Home

2. if there is no previous view to navigate to (i.e user in Home view), it should prompt the user with a dialog box asking if he wants to exit the app. That way users understand they can’t go further back.

Image 3: Clicking Android Back Button in Home view

Let’s develop the functionality

React native provides BackHandler API (there’s also BackAndroid but it’s deprecated) for detecting hardware back button presses. In order to handle the 2 aforementioned cases, we are going to create 1 method for each as shown below:

Go back to the previous view

// packages

import {BackHandler} from 'react-native';

* Attaches an event listener that handles the android-only hardware

* back button

*

*/

const handleAndroidBackButton = callback => {

BackHandler.addEventListener('hardwareBackPress', () => {

callback();

return true;

});

}; /*** Attaches an event listener that handles the android-only hardware* back button @param {Function} callback The function to call on click*/const handleAndroidBackButton = callback => {BackHandler.addEventListener('hardwareBackPress', () => {callback();return true;});}; /**

* Removes the event listener in order not to add a new one

* every time the view component re-mounts

*/

const removeAndroidBackButtonHandler = () => {

BackHandler.removeEventListener('hardwareBackPress', () => {});

} export {handleAndroidBackButton, removeAndroidBackButtonHandler};

Method handleAndroidBackButton adds an event listener to detect the press of ABB and accepts a callback function as an argument, in order for us to supply the desired functionality, in our case the navigation to the previous view. Pay attention the fact that we use return true inside the addEventListener function in order to prevent the default functionality of exiting the app. So we should add this when we do not want for the API to automatically close the app.

Method removeAndroidBackButtonHandler removes the previously added event listener in order to secure that we will not keep adding event listeners when we navigate back (most routing libraries will re-mount the view, causing a new listener to be added and if that happens, the application might glitch or even crash).

Let’s see an example of how to use these methods now, inside a view of our application. Simply invoke the handleAndroidBackButton method inside the constructor or componentDidMount and pass the callback function that will navigate the user to the previous view ( navigateBack ). Also invoke the removeAndroidBackButtonHandler method inside the componentWillUnmount lifecycle method.

// packages

import * as React from 'react'; // modules

import {

handleAndroidBackButton,

removeAndroidBackButtonHandler

} from './modules/androidBackButton'; class UserHistory extends React.Component {

constructor(props) {

super(props); this.state = {};

} componentDidMount() {

handleAndroidBackButton(navigateBack);

} componentWillUnmount() {

removeAndroidBackButtonHandler();

}

.

.

.

}

Display a modal prompting for app exit

// packages

import {Alert} from 'react-native'; const exitAlert = () => {

Alert.alert(

'Confirm exit',

'Do you want to quit the app?'

[

{text: 'CANCEL', style: 'cancel'},

{text: 'OK', onPress: () => BackHandler.exitApp()}

]

);

}; export {exitAlert};

Method exitAlert makes use of the Alert RN API that can display alert modals to the UI. We add the modal title: Confirm Exit , the modal’s main text: Do you want to quit the app? along with the 2 buttons that will appear to the user with their respective functionality. From left to right we will see over the UI a button with the text Cancel and a button with the text OK . Cancel button simply dismisses the modal (functionality is built in), while OK works with a callback function where we pass the exitApp method of Backhandler API.

This method ( exitAlert ) can be passed as a callback to the previous method ( handleAndroidBackButton ) inside the views that “there is no going back”. I.e. in Home view we will have the following code:

// packages

import * as React from 'react'; // modules

import {

handleAndroidBackButton,

exitAlert

} from './modules/androidBackButton'; class UserHistory extends React.Component {

constructor(props) {

super(props); this.state = {};

} componentDidMount() {

handleAndroidBackButton(exitAlert);

} .

.

.

}

For more details check the RN docs for backHandler and Alert APIs.