Skip to content Skip to sidebar Skip to footer

How To Close A React Navigation Modal With Multiple Screens In It

I'm using https://reactnavigation.org/ for navigation in a React Native app with a tab navigator as the main stack and a modal with two screens in it (for logging in and configurin

Solution 1:

I found a solution but it isn't perfect.

You can use the popToTop which will go back to the first Scene of your stack and than the goBack will close the modal.

navigation.popToTop();
navigation.goBack(null);

The problem with that is that it will mount again the first scene of the stack, so be sure you dont use setState in you willMount or didMount. Or prevent it.

That's the solution i'm going with for now. I keep looking for a better solution.

Solution 2:

Simple and easy solution for react-navigation 5.x (getParent docs):

navigation.getParent()?.goBack();

This works because it grabs the navigator's parent, which is the modal and what you want to dismiss.

NOTE: In older versions of 5.x this was called dangerouslyGetParent. That exists in newer 5.x versions, but is now deprecated. Use that if getParent isn't available in the version of react-navigation that you're using. It isn't actually dangerous: From react-navigation's documentation:

Reason why the function is called dangerouslyGetParent is to warn developers against overusing it to eg. get parent of parent and other hard-to-follow patterns.

Solution 3:

Original solution from https://github.com/react-navigation/react-navigation/issues/686#issuecomment-342766039, updated for React Navigation 4:

Create a DismissableStackNavigator:

importReactfrom'react';
import { createStackNavigator } from'react-navigation-stack';
exportdefaultfunctionDismissableStackNavigator(routes, options) {

  constStackNav = createStackNavigator(routes, options);

  constDismissableStackNav = ({navigation, screenProps}) => {
    const { state, goBack } = navigation;
    const props = {
      ...screenProps,
      dismiss: () =>goBack(state.key),
    };

    return (
      <StackNavscreenProps={props}navigation={navigation}
      />
    );
  }

  DismissableStackNav.router = StackNav.router;
  returnDismissableStackNav;
};

Usage:

  1. Creating your stack:
// modal with two screensconst Setup = StackNavigator(
  {
    Login: Login,
    SelectItems: SelectItems
  },
  {
    initialRouteName: 'Login'
    headerMode: 'none'
  }
);
  1. Call navigation.dismiss in your screens to close the modal stack.

Solution 4:

If you use react-navigation 4.x there is a method navigation.dismiss(). The method dismisses the entire stack and return to the parent stack

https://reactnavigation.org/docs/4.x/navigation-prop/#dismiss

Solution 5:

I was trying to figure this myself and the solution I ended up using was to use navigation.navigate()

Example this.props.navigation.navigate('name of screen you want to go');

Hope this helps!

Post a Comment for "How To Close A React Navigation Modal With Multiple Screens In It"