vmarquet
vmarquet

Reputation: 2532

Resetting the navigation stack when changing tab (StackNavigators nested in TabNavigator)

I have two StackNavigator. Movies:

const MoviesStackNavigator = createStackNavigator({
  Movies: Movies,
  MovieDetails: MovieDetails,
},{
  initialRouteName: 'Movies',
})

and actors:

const ActorsStackNavigator = createStackNavigator({
  Actors: Actors,
  ActorDetails: ActorDetails,
},{
  initialRouteName: 'Actors',
})

I am using them inside a TabNavigator:

const RootTabs = createBottomTabNavigator({
  Movies: {
    screen: MoviesStackNavigator,
    navigationOptions: {
      tabBarLabel: 'Movies'
    }
  },
  Actors: {
    screen: ActorsStackNavigator,
    navigationOptions: {
      tabBarLabel: 'Actors'
    }
  },
})

When the user changes tab, I want him to arrive to the root component of that tab (Movies or Actors), not to a stacked component (MoviesDetails or ActorsDetails). In other word, when a user quits a tab, the StackNavigator in that tab should be resetted to the root component.

My first approach was to use StackActions.reset when initializing the root component in a tab to try to reset the other tab (that the user just quit) but the library prevents interacting between navigators, at least in that way.

So, any ideas?

Upvotes: 1

Views: 1836

Answers (1)

vmarquet
vmarquet

Reputation: 2532

My solution was to use tabBarOnPress:

const RootTabs = createBottomTabNavigator({
  Movies: {
    screen: MoviesStackNavigator,
    navigationOptions: {
      tabBarLabel: 'Movies',
      tabBarOnPress: ({navigation, defaultHandler}: any) => {
        navigation.navigate('Actors')
        defaultHandler()
      },
    }
  },
  Actors: {
    screen: ActorsStackNavigator,
    navigationOptions: {
      tabBarLabel: 'Actors',
      tabBarOnPress: ({navigation, defaultHandler}: any) => {
        navigation.navigate('Movies')
        defaultHandler()
      },
    }
  },
})

Upvotes: 8

Related Questions