Hardware back button handling using BackHandler and navigation properties, without deprecated BackAndroid or Navigator

suggest change

This example is the back behavior most flows expect. Add the following to each screen, depending on the behavior you want. navigation.goBack is the react-navigation API. There are two cases:

  1. If there is more than one screen on the stack, the device back button shows the previous screen.
  2. If there is only one screen on the stack, the device back button exits the app.

Case 1: Show previous screen

import { BackHandler } from 'react-native';

constructor(props) {
    super(props)
    this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
}

componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}

componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
}

handleBackButtonClick() {
    this.props.navigation.goBack(null);
    return true;
}

Important: Don’t forget to bind method in constructor and to remove listener in componentWillUnmount.

Case 2: Exit App

In this case, do not handle the back button on the screen where the app should exit. Returning true from a listener consumes the event, and the app will not exit.

Important: This must be the only screen on the stack.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents