How to use BackHandler with React Navigation in React Native

Last Updated on August 22, 2019.

On Android devices, users prefer hardware back button to navigate back. Even though the actions of the back button is normally desirable, sometimes you may need to customize the action of the hardware button.

In this blog post, Let’s see how to customize the back button actions using BackHandler and react-navigation library. The BackHandler API of react native is used to detect when the hardware back button of an Android device is pressed.

In the following react native example I am customizing the action of the hardware back button so that the app quits. With react-navigation and BackHandler, we can subscribe to navigation life cycle updates to add a custom listener.

mport React, { Component } from "react";
import { View, Text, BackHandler } from "react-native";

export default class componentName extends Component {
 _didFocusSubscription;
  _willBlurSubscription;

  constructor(props) {
    super(props);
    this.state = {};
 this._didFocusSubscription = props.navigation.addListener('didFocus', payload =>
      BackHandler.addEventListener('hardwareBackPress', this.handleBackPress)
    );
  }

  componentDidMount() {
    this._willBlurSubscription = this.props.navigation.addListener('willBlur', payload =>
      BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress)
    );
  }

  componentWillUnmount() {
    this._didFocusSubscription && this._didFocusSubscription.remove();
    this._willBlurSubscription && this._willBlurSubscription.remove();
  }

  handleBackPress = () => {
    BackHandler.exitApp(); // works best when the goBack is async
    return true;
  };
  render() {
    return (
      <View>
        <Text> textInComponent </Text>
      </View>
    );
  }
}

Still, have doubts? you can go through official documentation of react navigation here.

1 thought on “How to use BackHandler with React Navigation in React Native”

  1. Pingback: How to Make the App Quit When Hardware Back Button is pressed in React Native (Android) - REACT NATIVE FOR YOU

Leave a Reply

%d bloggers like this: