How to Make the App Quit When Hardware Back Button is pressed in React Native (Android)

Last Updated on December 11, 2020.

Update: Please check out my latest blog post on Android BackHandler here.

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.

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.

Go through the example given below to have good understanding.

import React, { Component } from "react";
import { View, Text, BackHandler } from "react-native";
 export default class componentName extends Component {   
constructor(props) {     
super(props); 
this.state = {};   }
 componentDidMount() {     
BackHandler.addEventListener("hardwareBackPress", this.handleBackPress);   }
 componentWillUnmount() {     BackHandler.removeEventListener("hardwareBackPress", this.handleBackPress);   }
  handleBackPress = () => {     BackHandler.exitApp(); // works best when the goBack is async     return true;   };
   render() {     
return (       
<View>         
<Text> textInComponent </Text>       
</View>     
);   
} }

Leave a Reply

%d bloggers like this: