Handling Android Back Button Press in React Native

Android Back Button

When the user presses the Android hardware back button in React Native, react-navigation will pop a screen or exit the app if there are no screens to pop. This is the sensible default behavior, but there are situations when you might want to implement custom handling. This is where handling the android back button is useful. You can also check react-navigation-backhandler library to handle the back press.

Event Listener for Back Button Press

To handle the Android Back Button Press in the React Native we have to register the hardwareBackPress event listener with a callback function, which will be called after pressing the Back Button. We should also remove the listener when we are jumping out from the screen (where we have added the listener) because sometimes after going to the next screen or any other screen the listener remains active in the background if the last screen is in the stack and not killed by the system.

The event subscriptions are called in reverse order (i.e. last registered subscription first), and if one subscription returns true then subscriptions registered earlier will not be called. 

Add hardwareBackPress Event Listener

BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);

Remove hardwareBackPress Event Listener

BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);

Handle the event

handleBackButtonClick() {
  // After clicking on Back Button 

  // To go to any other screen
    this.props.navigation.navigate('ThirdPage');

  // To popup the default screen 
    this.props.navigation.goBack(null);

  // To exit from your App
    BackHandler.exitApp();
  // Returning true/false is described below
    return true;
  }

Returning true from handleBackButtonClick denotes that we have handled the event, and react-navigation’s listener will not get called, thus not popping the screen. Returning false will cause the event to bubble up and react-navigation’s listener will pop the screen.

Why not use component lifecycle methods?

At first, you may be inclined to use componentDidMount to subscribe for the back press event and componentWillUnmount to unsubscribe. The reason, why we do not use them, is that they are not generally called when entering or leaving a screen.

More specifically, consider a StackNavigator with screens A and B. After navigating to A, its componentDidMount is called. When pushing B, its componentDidMount is also called, but A remains mounted and its componentWillUnmount is therefore not called.

Similarly, when going back from B to AcomponentWillUnmount of B is called, but componentDidMount of A is not because A remained mounted the whole time.

So here was the big discussion. Now Let’s start with the code.

In our example, we are going from FirstPage to SecondPage using navigate and after clicking Back Button on SecondPage we will navigate to ThirdPage with an alert. We have also used this.props.navigation.goBack(null); on ThirdPage to popup the default screen. So let’s get started.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependencies

To install the dependencies open the terminal and jump into your project

cd ProjectName

1. Install react-navigation dependency to import createAppContainer

npm install react-navigation --save

2. Other supporting libraries for react-navigation

npm install react-native-gesture-handler react-native-safe-area-context @react-native-community/masked-view react-native-screens react-native-reanimated --save

3. Install react-navigation-stack to import createStackNavigator

npm install react-navigation-stack --save

These commands will copy all the dependencies into your node_module directory.

CocoaPods Installation

Please use the following command to install CocoaPods

cd ios && pod install && cd ..

Project File Structure

To start with this Example you need to create a directory named pages in your project and create three files FirstPge.js, SecondPage.js, and ThirdPage.js.

Code to Handle Android Back Button

Now Open App.js in any code editor and replace the code with the following code

App.js

//This is an example code to handle Android back button press// 
import React, { Component } from 'react';
//import react in our code.

//Import react-navigation
import { createAppContainer } from 'react-navigation';
import { createStackNavigator} from 'react-navigation-stack';

//Import external files
import FirstPage from './pages/FirstPage';
import SecondPage from './pages/SecondPage';
import ThirdPage from './pages/ThirdPage';

const App = createStackNavigator({
  //Constant which holds all the screens like index of any book 
    FirstPage: { screen: FirstPage }, 
    //First entry by default be our first screen if we do not define initialRouteName
    SecondPage: { screen: SecondPage }, 
    ThirdPage: { screen: ThirdPage }, 
  },
  {
    initialRouteName: 'FirstPage',
  }
);
export default createAppContainer(App);

Open pages/FirstPage.js in any code editor and replace the code with the following code.

FirstPage.js

// First screen which will be used to navigate to second screen
import React, { Component } from 'react';
//import react in our code. 
import { StyleSheet, View, Button, TextInput} from 'react-native';
//import all the components we are going to use.

export default class FirstPage extends Component {
  static navigationOptions = {
    //Setting the header of the screen
    title: 'First Page',
  };
  render() {
    const { navigate } = this.props.navigation;
    return (
      <View style={styles.container}>
        {/*Button to go to the next SecondPage*/}
        <Button title='Go next'
        onPress={() =>navigate('SecondPage')}
        />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    padding:16
  },
});

Open pages/SecondPage.js in any code editor and replace the code with the following code.

SecondPage.js

// Second Screen which will be used to show backpress
import React, { Component } from 'react';
//import react in our code.
import { StyleSheet, View, Text ,BackHandler } from 'react-native';
//import all the components we are going to use.

export default class SecondPage extends Component {
  constructor(props) {
    super(props)
    //Binding handleBackButtonClick function with this
    this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
  }
  componentDidMount() {
    // This is the first method in the activity lifecycle
    // Addding Event Listener for the BackPress 
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
  }
  componentWillUnmount() {
    // This is the Last method in the activity lifecycle
    // Removing Event Listener for the BackPress 
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
  }
  handleBackButtonClick() {
    // Registered function to handle the Back Press
    // We are generating an alert to show the back button pressed
    alert('You clicked back. Now Screen will move to ThirdPage');
    // We can move to any screen. If we want
    this.props.navigation.navigate('ThirdPage');
    // Returning true means we have handled the backpress
    // Returning false means we haven't handled the backpress
    return true;
  }
  static navigationOptions = {
     //Setting the header of the screen
    title: 'Second Page',
  };
  render() {
    const { navigate } = this.props.navigation; 
    return (
      <View style={styles.container}>
        <Text>
          You are on SecondPage
        </Text>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Open pages/ThirdPage.js in any code editor and replace the code with the following code.

ThirdPage.js

// Third Screen which will be used to show backpress
import React, { Component } from 'react';
//import react in our code.
import { StyleSheet, View, Text ,BackHandler } from 'react-native';
//import all the components we are going to use.

export default class ThirdPage extends Component {
  constructor(props) {
    super(props)
    //Binding handleBackButtonClick function with this
    this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
  }
  componentDidMount() {
    // This is the first method in the activity lifecycle
    // Addding Event Listener for the BackPress 
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
  }
  componentWillUnmount() {
    // This is the Last method in the activity lifecycle
    // Removing Event Listener for the BackPress 
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
  }
  handleBackButtonClick() {
    // Registered function to handle the Back Press
    // To popup the default screen while going back you can use goBack
    this.props.navigation.goBack(null);
    // To exit from your App you can use BackHandler.exitApp();. 
    // Just comment the above line and uncomment the below to use it 
    //BackHandler.exitApp();
    // Returning true means we have handled the backpress
    // Returning false means we haven't handled the backpress
    // Try to make it false also
    return true;
  }
  static navigationOptions = {
    title: 'Third Page',
    //Sets Header text of Status Bar
  };
  render() {
    const { navigate } = this.props.navigation; 
    return (
      <View style={styles.container}>
        <Text>
          You are on Third Page
        </Text>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

To Run the React Native App

Open the terminal again and jump into your project using.
cd ProjectName
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running
react-native run-ios (macOS only).

Output Screenshots

Output in Online Emulator

That was the way to handle the Android Back Button. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂


Related Posts

4 thoughts on “Handling Android Back Button Press in React Native”

  1. you can set condition for costume function that u write for hardware button , for example when ( for example for React Native Router Flux ) Actions.currentScene === ‘Home’ do something or other conditions u want .

    Reply
  2. sir i’m not getting anything ,when i passed this.props.navigation.navigate(‘ThirdPage’); its not redirecting to another page (i declared my page instead of ‘ThirdPage’)

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.