Search code examples
react-nativereact-navigationstack-navigator

Reset StackNavigator inside createBottomTabNavigator on tabBarOnPress


I have this structure:

bottomTabNavigator:

  • Screen 1
  • Screen 2
    • Screen A
    • Screen B

When the user navigates to Screen B, then goes to Screen 1 and go back to Screen 2, he goes directly in B, how can I reset the stack using the tabBarOnPress function to force the user to go back to A?

I'm using react-navigation 3.0.9, I tried a few codes but I got errors and I think it is due to the version.

My code structure:

const Navigator = createBottomTabNavigator({
        Screen1: {
            screen: Screen1,
            navigationOptions: () => ({
                tabBarOnPress...
            })
        },
        Screen2: {
            screen: Screen2,
            navigationOptions: () => ({
                tabBarOnPress...
            })
        }
})


Solution

  • As given by the explanation here. you can do a reset action when clicking a tab like this:

    import { StackActions, NavigationActions } from 'react-navigation';
    
    const resetAction = StackActions.reset({
      index: 0,
      actions: [NavigationActions.navigate({ routeName: 'Profile' })],
    });
    this.props.navigation.dispatch(resetAction);
    

    So you should do something like:

    tabBarOnPress{() => StackActions.reset({
      index: 0,
      actions: [NavigationActions.navigate({ routeName: 'Screen1' })],
    })};