Example of BackAndroid along with Navigator
suggest changeThis example uses React Native’s BackAndroid with Navigator. Both APIs were later deprecated (BackHandler and other navigators replace them).
componentWillMount registers a listener for the hardware back button. If another route is on the stack, it goes back; otherwise it keeps the default behaviour.
More information is in the BackAndroid docs and the Navigator docs.
import React, { Component } from 'react'; // eslint-disable-line no-unused-vars
import {
BackAndroid,
Navigator,
} from 'react-native';
import SceneContainer from './Navigation/SceneContainer';
import RouteMapper from './Navigation/RouteMapper';
export default class AppContainer extends Component {
constructor(props) {
super(props);
this.navigator;
}
componentWillMount() {
BackAndroid.addEventListener('hardwareBackPress', () => {
if (this.navigator && this.navigator.getCurrentRoutes().length > 1) {
this.navigator.pop();
return true;
}
return false;
});
}
renderScene(route, navigator) {
this.navigator = navigator;
return (
<SceneContainer
title={route.title}
route={route}
navigator={navigator}
onBack={() => {
if (route.index > 0) {
navigator.pop();
}
}}
{...this.props} />
);
}
render() {
return (
<Navigator
initialRoute={{ title: 'Initial Scene', index: 0 }}
renderScene={this.renderScene.bind(this)}
navigationBar={
<Navigator.NavigationBar
style={{backgroundColor: 'gray'}}
routeMapper={RouteMapper} />
} />
);
}
};
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents