2
votes

I almost searched everywhere about BackHandler in react-native but could not get much information about this.

I have 4 screens -
1) Splash screen that decides if I don't have a login token go to login screen else to home screen
2) login screen
3) home screen
4) detail screen

2 scenarios -

1) When I am logged in, I am in the home screen. Clicking on an item in home screen will take me to the detail screen.

So in detail screen, I press back button, I goto Home screen and pressing back button in Home screen will exit the app.

2) When I am not logged in, I am in the login screen. Pressing back button shall exit the app.

How should I use the BackHandler for the above scenario?

1
For exiting the app refer the static exit() facebook.github.io/react-native/docs/backhandler#exitapp - Aravind S
your issue fixed here? - Aravind S
No... I actually just dont want to exit app but also handle going back to views - user9765778
For naviagating to a view, try onPress={() => navigate('home ')} - Aravind S
No i mean in my above explaination, If i want to go back from details to home, i need to handle back press there and not exit the app - user9765778

1 Answers

2
votes

try to set this:

  componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
  }

  handleBackPress = () => {
    this.props.navigation.navigate('Home');
    return true;
  };

in Home if you press Back always go to Home no? (never hurts to try :-D)