Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save abhishekgargx/447727a32e284c24346ec6d1a83feefe to your computer and use it in GitHub Desktop.
Save abhishekgargx/447727a32e284c24346ec6d1a83feefe to your computer and use it in GitHub Desktop.
React Native | react-native-router-flux | Redux | Android Back button listener ,handle back press on android while using react native.
// below code works with Android + react native + react-native-router-flux
// this is final index.js file code from where control whole app navigation
import { BackHandler, ToastAndroid } from 'react-native';
import React,{Component} from 'react';
import { Router, Scene, Actions } from 'react-native-router-flux';
import { Provider } from 'react-redux';
// as per your compoenents import them accordingly
import Home from './home';
import OtherScreen from './OtherScreen';
//variable
var backButtonPressedOnceToExit = false;
export default class App extends Component {
componentWillMount(){
BackHandler.addEventListener('hardwareBackPress', this.onBackPress.bind(this));
}
componentWillUnmount(){
BackHandler.removeEventListener('hardwareBackPress', this.onBackPress.bind(this));
}
onBackPress() {
if (backButtonPressedOnceToExit) {
BackAndroid.exitApp();
} else {
if (Actions.currentScene !== 'Home') {
Actions.pop();
return true;
} else {
backButtonPressedOnceToExit = true;
ToastAndroid.show("Press Back Button again to exit",ToastAndroid.SHORT);
//setting timeout is optional
setTimeout( () => { backButtonPressedOnceToExit = false }, 2000);
return true;
}
}
}
render() {
return(
<Provider store={store}>
<Router backAndroidHandler={this.onBackPress} >
<Scene key="root" }>
<Scene key="Home" component={Home} initial={true} />
<Scene key="OtherScreen" component={OtherScreen} />
</Scene>
</Router>
</Provider>
);
}
}
AppRegistry.registerComponent('YourAppNameAccordingToPackageJSON', () => App);
@Jogayathri
Copy link

now got output for this one

@abhishekgargx
Copy link
Author

@abdullateef97 from line 30 - 36, i taking back press input two times from user to confirm he want to go back or not. it is nothing more than user experience, for example if he mistakenly pressed backpress application wont exit, it will ask to press back again with in 2 sec to exit . kind of confirmation . like we usually saw in website (do you want to exit ) yes or no press dailog.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment