Setting up the Back Android Navigation in React-Native

Background

Browsing through the different sites plus even React-Native documentation setting up the Back Android Navigation is not as straight forward as anyone would wish, so i dived in and lucky enough i landed on a tutorial by Scott Luptowski https://medium.com/the-many/handling-android-back-button-events-in-react-native-with-custom-components-b33c63b0633b#.wm8x80t13

Where he talks about using the native BackAndroid api and handling side Effects using the React Side Effect library from yours truly Dan Abramov the authour of the famous redux library, Scott was kind enough to package the solution into a react-native library.

Much as the library is very useful if you are like me and your have an application with many routes you might wonder about the route from which to call the library from.

So after playing with it i realised two things, if you want custom behaviours at specific routes on taping the back button on the phone hardware you will need add the library from that specific route, and for the general behaviour of the back button you can include it one in the home route (In my case i was using redux library too) so i included it in the home container.

So without wasting much time, let’s dive into the code.

Install the react-native-android-back-button using npm or yarn

npm install --save react-native-android-back-button

Import the library and add the AndroidBackButton component(It is a non UI component), AndroidBackButton strictly requires an onPress prop.

//import the AndroidBackButton
import React, {Component} from 'react';
import {View} from 'react-native';
import AndroidBackButton from 'react-native-android-back-button';
....
class Home extends Component {
constructor(props){
super(props);
....
}
onBackButtonPress = () => {
if (this.props.navigator.getCurrentRoutes().length > 1) {
// can add custom behaviour that which is truthy or return
// true
      this.props.navigator.pop();
return true;
}
return false;
}
return (){
render(
<View>
.....
<AndroidBackButton onPress={this.onBackButtonPress} />
    </View>
);
}
}

Side Notes

I tested react-native-android-back-button with the native navigator.

On pressing the back button if the result is truthy nothing will happen unless a specific action is specified , if the result is falsey on pressing the back button the application will close even if an action is specified.