I have a Navigator
in an Android react native application.
I'm using navigator.push()
to navigate to a different page. It would seem natural that the back button would pop the navigator and to go back one page, but that's not what's happening (it quits the app).
Do the react-native Navigator
really has no back button support, do I need to plug it myself with a BackAndroid
?
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.
By default React Navigation will handle the Android back button for you, however we'll need to override the defaults. If you're at the top of the stack and press the android back button the application will close. If you've navigated within the stack anywhere then the screen will pop.
The Backhandler API detects hardware button presses for back navigation, lets you register event listeners for the system's back action, and lets you control how your application responds. It is Android-only.
By default, only one handler is fired per hardware back button press. The priority value is used to determine which callback should be called. This is useful because if you have a modal open, you likely would not want the modal to close and the app to navigate backwards when pressing the hardware back button.
In addition to answer above, handling code should be something like this
var navigator; React.BackAndroid.addEventListener('hardwareBackPress', () => { if (navigator && navigator.getCurrentRoutes().length > 1) { navigator.pop(); return true; } return false; });
in render code:
<Navigator ref={(nav) => { navigator = nav; }} />
Not sure when the API changed but as of react native 0.31 (potentially earlier versions as well) BackAndroid is a component that must be imported from react-native:
import {..., BackAndroid} from 'react-native'
Also be sure to remove the listener on componentWillUnmount:
componentWillUnmount(){ BackAndroid.removeEventListener('hardwareBackPress', () => { if (this.navigator && this.navigator.getCurrentRoutes().length > 1) { this.navigator.pop(); return true; } return false; }); }
*UPDATE: In react native 0.44 this module has been renamed to BackHandler
. Navigator
has also been officially deprecated but can still be found here: https://github.com/facebookarchive/react-native-custom-components
import { BackHandler } from 'react-native';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With