'How to reach to the top of the stack when pressing tab in react native?
I got 5 buttons of tabs navigator. You can consider them as a,b,c,d,e
The thing is when I am in a I will goes into the screen called a.1. So I am basically in the a.1.
Inside the a.1 screen I can goes into b or c or ...
So I will goes into b from a.1screen
The thing is that when I press tab navigator button for a. I reached to the a.1 rather than reaching directly to a.
How can I avoid this behavior
Solution 1:[1]
const a = () => (
<Stack.Navigator initialRouteName={"a1"}>
<Stack.Screen name={"a1"} component={a1} />
<Stack.Screen name={"a2"} component={a2} />
</Stack.Navigator>
);
const b = () => (
<Stack.Navigator>
<Stack.Screen name={"b1"} component={b1} />
<Stack.Screen name={"b2"} component={b2} />
</Stack.Navigator>
);
const TabNavigator = () => {
return (
<Tab.Navigator>
<Tab.Screen name="a" component={a} />
<Tab.Screen name="b" component={b} />
<Tab.Screen name="c" component={c} />
</Tab.Navigator>
);
};
That is called 'NestedNavigation'. In above navigation, the bottom tab will appear in every srceens. If you don't want that feature, you can add 'Tab' into 'Stack'. Like this.
const TabNavigator = () => (
<Tab.Navigator>
<Tab.Screen name="a" component={a} />
<Tab.Screen name="b" component={b} />
<Tab.Screen name="c" component={c} />
</Tab.Navigator>
);
const StackNavigator = () => {
return (
<Stack.Navigator initialRouteName={"TabNavigator"}>
<Stack.Screen name={"TabNavigator"} component={TabNavigator} />
<Stack.Screen name={"a1"} component={a1} />
<Stack.Screen name={"a2"} component={a2} />
<Stack.Screen name={"b1"} component={b1} />
<Stack.Screen name={"b2"} component={b2} />
</Stack.Navigator>
);
};
Even if my answer does not directly answer your question, I hope it might give u some idea of nested navigation.
You can use 'initialRouteName' to show the initialScreen of any navigators.
In case, I mis-understood your question. Here is how to overwrite 'Tab Navigation' onPress function.
<Tab.Screen
name="Chat"
component={Chat}
listeners={({ navigation, route }) => ({
tabPress: (e) => {
// Prevent default action
e.preventDefault();
// Do something with the `navigation` object
navigation.navigate('AnotherPlace');
},
})}
/>
Solution 2:[2]
you can achieve it by resetting the stack when you leave the tab a, so that you are in the first screen when you come back to tab a. Here's the official documentation and example: https://www.reactnativeschool.com/reset-stack-inside-tab-after-leaving-tab
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Drampo dvlpmnt |
