Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 configuring the app).

I can't for the life of me figure out how to close the modal from the second screen (SelectItems). From the first screen in the modal I can close it with navigation.goBack().

Both modal screens need a close button. Is there a way to just return back to whatever tab the user was on?

Thanks in advance for any help.

const Tabs = TabNavigator(
  {
    Search: { screen: Search },
    Settings: { screen: Settings }
  }
);

// modal with two screens
const Setup = StackNavigator(
  {
    Login: {
      screen: Login
    },
    SelectItems: {
      screen: SelectItems
    }
  },
  {
    initialRouteName: 'Login'
  }
);

const RootStack = StackNavigator(
  {
    Main: {
      screen: Tabs
    },
    Setup: {
      screen: Setup
    }
  },
  {
    mode: 'modal',
    headerMode: 'none'
  }
);
like image 732
Alex Dunae Avatar asked Apr 12 '18 19:04

Alex Dunae


2 Answers

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.

like image 144
Alexandre Rivest Avatar answered Oct 02 '22 21:10

Alexandre Rivest


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.

like image 37
SamB Avatar answered Oct 02 '22 23:10

SamB