Hardware back button handling using BackHandler and navigation properties, without deprecated BackAndroid or Navigator
suggest changeThis 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:
- If there is more than one screen on the stack, the device back button shows the previous screen.
- 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents