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
?
In order to clean the code using my knowledge and previous answers, here is how it should look like:
Yes, you have to handle the back button yourself. I think the main reason for this is you may want to do different things with the back button instead of just moving back through the stack. I don't know if there are plans to incorporate back button functionality in the future though.
In addition to answer above, handling code should be something like this
in render code:
Don't forget bind [this]
The correct answer should be:
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:
*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-componentsI have created a GitHub repo that will provide you a sample project of how to handle the Android Back Button.
You can clone / download the repo at:
Android Back Button Sample Project
But here are some sample codes on how I handle the android back button
The following code is for my initial screen when user starts my app. Pressing the back button button here would show an alert of which will ask the user whether the user would like to leave the app.
The following code is a screen for which when the user presses the back button, it go back the previous screen: