Handling back button in React Native, Navigator on Android
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';
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; }} />
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.