Ayan
Ayan

Reputation: 2918

Unmount all previously mounted screens to exit the app on back press

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 });
};

Upvotes: 0

Views: 1014

Answers (1)

LonelyCpp
LonelyCpp

Reputation: 2673

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

Upvotes: 3

Related Questions