Search code examples
androidiosreact-nativereact-navigationreact-navigation-stack

Weird behaviour with Double Tapping BottomTabNavigator - React Navigation


I use React Navigation to do my Navigation in my mobile app and I have a structure navigation like this:

const AccountStack = createStackNavigator(
    {
        Account: AccountView,
        ...

    },
    {
        initialRouteName: 'Account',
        headerMode: 'screen',
        ....
    }
)

const SearchUsersStack = createStackNavigator(
    {
        SearchUsers: SearchUsersView,
        UserProfile: UserProfileView,
        FriendsOfUser: FriendsOfUserView
    },
    {
        ...
    }
)

const AccountModalStack = createStackNavigator(
    {
        AccountStack: AccountStack,
        SearchUsersStack: SearchUsersStack,
    },
    {
        initialRouteName: 'AccountStack',
        headerMode: 'none',
        mode: 'modal',

    }
)

const MainApp = createBottomTabNavigator(
    {
        MainHome: HomeStack,
        MainPlay: PlayStack,
        MainAccount: AccountModalStack
    },
    {
        ...
    }
)

If I'm in the "search User" stack (for example, in SearchUserView) and I click on the "Account" icon in the bottom tab navigator, the stack will dismiss correctly and I will return to my "account" view.

However, if I am in one of the routes of my AccountStack and I click on the "Account" icon in the bottom tab navigator, the stack does not dismiss. So if I'm very far in the account stack, I have to go back with the back arrow.

Why does it work when I'm in the SearchUserStack but not when I'm in my AccountStack ?

I hope to find help!

Thank you !

Viktor


Solution

  • You can override what happens when you tap on a tab, which you can do via the navigationOptions of each navigator in the tab bar.

    const AccountModalStack = createStackNavigator(
      {
        AccountStack: AccountStack,
        SearchUsersStack: SearchUsersStack,
        // ...
      },
      {
        initialRouteName: 'AccountStack',
        navigationOptions: {
          tabBarOnPress: ({ navigation }) => {
            navigation.navigate({
              routeName: 'AccountStack', // navigates to the initial route
              action: navigation.popToTop(), // go to the top of the stack of that route
            })
          },
          // ...
        },
        // ...
      }
    )
    

    It's likely that the tab by default attempts to simply navigate to the initial route, without resetting the stack.