Supriya Gorai
Supriya Gorai

Reputation: 372

How to Reset the stacks on tab change inside bottomTabNavigayor?

Snack

I have bottomTabNavigator in my tab and inside each tab I have stacks. I want to reset the stack whenever I click on another tab.

Tab Navigator-

Tab 1 - |_Stack Navigator

     - Screen 1

     - Screen 2

Tab 2 - |_Stack Navigator

     - Screen 3

     - Screen 4

Tab 3 - |_Stack Navigator

     - Screen 5
     - Screen 6

The present scenario is, . Suppose I am on tab 1 - I navigate to Screen 2 from screen 1 . Then I click to Tab 2 . Now if I again click on Tab 1, Screen 2 is showing instead of Screen 1.

Similar thing is happening on each tab.

I want to reset the tab on each tab click.

Please help.

I am using -

"dependencies": { "@react-native-community/cli": "^4.1.0", "@react-native-community/masked-view": "^0.1.6", "@react-navigation/bottom-tabs": "^5.0.5", "@react-navigation/native": "^5.0.5", "@react-navigation/stack": "^5.0.5", "react": "16.9.0", "react-native": "0.61.5", "react-native-gesture-handler": "^1.6.0", "react-native-gifted-chat": "^0.13.0", "react-native-reanimated": "^1.7.0", "react-native-safe-area-context": "^0.7.3", "react-native-screens": "^2.0.0-beta.7", },

Upvotes: 3

Views: 2480

Answers (3)

Harsh Vaid
Harsh Vaid

Reputation: 189

If you are using navigation version 4 or less, Then I have a very simple way to do it.

 tabBarOnPress:({ navigation }) => {
      navigation.navigate(HomeStack,{screen:navigation.state.routes[0].routeName});
       navigation.popToTop();
    },

Upvotes: 2

Supriya Gorai
Supriya Gorai

Reputation: 372

Update the latest version of react-navigation and its dependencies and use this solution, this worked for me.

<AppTabs.Screen
  name="TabScreen1"
  listeners={({ navigation }) => ({
    tabPress: () => {
      navigation.navigate('Main1', { screen: 'Main2' });
    },
  })}
/>

Upvotes: 1

Victor
Victor

Reputation: 4199

You could ovverride tabBarOnPress to get control of the tab click and reset the stack manually or use some other tricks.

A possible solution should be

navigationOptions: ({ navigation }) => ({
  tabBarOnPress: ({ scene, jumpToIndex }) => {
    const { route, focused, index } = scene;
    if (focused) {
      if (route.index > 0) {
        const { routeName, key } = route.routes[1]
        navigation.dispatch(NavigationActions.back({ key }))
      }
    } else {
      jumpToIndex(index);
    }
  },
});

You may need to update this code for v5. (Same goes for solutions below)

Refer more solutions here

Upvotes: 0

Related Questions