React Navigation TabNavigator: Reset previous tab on tab change
Solution for version 5.x.x and version 6.x.x:
Pass a listener to the screen component:
<Tab.Screen
name="homeTab"
component={HomeStackScreen}
listeners={tabBarListeners}
/>
Then on this listener, navigate the user every time when he presses the tab:
const tabBarListeners = ({ navigation, route }) => ({
tabPress: () => navigation.navigate(route.name),
});
Credits: https://github.com/react-navigation/react-navigation/issues/8583
Solution for version 4.x.x:
tabBarOnPress: ({ navigation }) => {
navigation.popToTop();
navigation.navigate(navigation.state.routeName);
}
Credits: https://github.com/react-navigation/react-navigation/issues/1557
Solution for versions 2.x.x and 3.x.x:
The problem is that when I reset the route, I need to pass the navigation action of the previous routeName (leaving tab) and to dispatch a new navigation action for the next route:
tabBarOnPress: ({ previousScene, scene }) => {
const tabRoute = scene.route.routeName;
const prevRouteName = previousScene.routes[0].routeName;
navigation.dispatch(NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({
routeName: prevRouteName
}),
],
}));
navigation.dispatch(NavigationActions.navigate({
routeName: tabRoute
}));
}
use unmountOnBlur option it works for all types of navigators , stack navigator , drawer navigator , bottomtab navigator
<Tab.Screen name="Home" component={DrawerNavigator} options={{unmountOnBlur:true}}/>
pass unmountOnBlur in the options prop of the screen of the navigator