React Native - Android BackHandler - How to implement this.OnMainScreen and this.goBack

5.8k Views Asked by At

I have splash screen on my apps, so I want to exit the apps when we click android back button from the main page (not go back to splash screen). So I want to implement this method from react-native tutorial.

if (!this.onMainScreen()) {
    this.goBack();
    return true;
}
return false;

Is there anyone can help me how to implement onMainScreen(), and goBack() functions? Thank you for the help.

2

There are 2 best solutions below

1
On

you should be able to use this function

function getCurrentRouteFromState(navigationState): NavigationRouteConfigMap {
  const route = navigationState.routes[navigationState.index];
  // dive into nested navigators
  if (route.routes) {
    return getCurrentRouteFromState(route);
  }
  return route;
}

pass it your navigation state and access the routeName member on the resulting object:

let screenName = getCurrentRouteFromState(state).routeName then you can compare the screen name with your main screen name and decide what to do.

4
On

So, On your main page(I think which is your Main.js)

import { BackHandler } from 'react-native';    
componentWillMount(){
BackHandler.addEventListener('hardwareBackPress', function() {
  BackHandler.exitApp();
});
}