0

I have a requirement in which I need to exit the app when the back button is pressed. Basically I tried with the BackHandler API, which worked but with certain limitations. So in my case, I feel the best way is to unmount all previously mounted components so the current screen becomes the first screen in the stack.

I have the following screens:

Login
OtpVerification
Name
Email
. . . and more

What I need is that when I am on the Name screen, if someone presses the back button, the app should exit. But if someone is on the Email screen, the user should be able to go back upto Name screen only.

Snippets using BackHandler

constructor(props) {
    super(props);
    .
    .
    BackHandler.addEventListener("hardwareBackPress", this._handleBackPress);
}
.
.
.
.
_handleBackPress = () => {
    BackHandler.exitApp();
};
.
.
.
.
_onPress = () => {
    BackHandler.removeEventListener("hardwareBackPress", this._handleBackPress);
    this.props.navigation.navigate("Email", { name: this.state.name });
};
Ayan
  • 2,738
  • 3
  • 35
  • 76

1 Answers1

3

The solution to this would be to reset the stack navigator before navigating to the Name screen.

Use the reset action in react-navigation to do this. documentation

A quick example of a function that does this is -

react-navigation 5 - use CommonActions

import { CommonActions } from "@react-navigation/native";

reset = (routeName) => {
  return navigation.dispatch(
    CommonActions.reset({
      index: 0,
      routes: [{ name: routeName }],
    })
  );
};

react-navigation v4.x

reset = (routeName) => {
  return this.props.navigation.dispatch(
    NavigationActions.reset({
      index: 0,
      actions: [NavigationActions.navigate({ routeName })],
    })
  );
};

put this in the OtpVerification screen and call reset('NameScreen') when navigating to NameScreen

related answer - https://stackoverflow.com/a/43121263/3262983

LonelyCpp
  • 2,533
  • 1
  • 17
  • 36
  • this doesnt look like its for version 5. Also am not sure if this is going to exit the app as I tried something similar to this and it is always taking me to Login screen. – Ayan Feb 22 '20 at 18:00
  • I've added an example for version 5. Try it :) – LonelyCpp Feb 22 '20 at 18:04
  • So how should I call reset? Before `this.props.navigation.navigate("NameScreen");` – Ayan Feb 22 '20 at 18:14
  • don't call navigate! reset will navigate to whatever screen you give it. just call `reset("NameScreen");` – LonelyCpp Feb 22 '20 at 18:47
  • Great!! It does what I was looking for. Just one thing, when my app exits, it stays in the background. Any workaround to **exit it completely**? – Ayan Feb 23 '20 at 05:48
  • 1
    It does actually close the app completely. If you're talking about the "recent apps" in android, that will require some android specific config. https://stackoverflow.com/questions/3762763/how-to-remove-application-from-recent-application-list – LonelyCpp Feb 23 '20 at 08:16