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'
}
);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With