'React navigation 4, bottom tab navigator: how to open the initial route every time the app is re-opened from the background
Current Behavior
I have a TabNavigator with 4 tabs, each tab is a stackNavigator, and for now each stackNavigator has only one screen: home, maps, reservations, profile. I'm using React Navigation 4. In every tab I put the navigationOption tabBarOnPress to navigate between the screens, so in this way the backBehavior: 'history' makes sense.
const TabNavigator = createBottomTabNavigator(
{
Home: {
screen: HomeStack,
navigationOptions: {
tabBarOnPress: ({navigation}) => {
navigation.navigate('Home')
},
}
},
//other tabs
},
{
initialRouteName: 'Home',
backBehavior: 'history'
}
)
But if I navigate between screens maybe in the order HOME -> PROFILE -> HOME -> MAPS, the stack of the routers is PROFILE, HOME, MAPS, because of the behavior of the navigate function. In a similar way, when we are on an android device and push the back button, the order of the visited screens is MAPS -> HOME -> PROFILE and if we push on the back button again we exit from the app, putting it in the background. Now, coming back in the app, the opened screen is PROFILE, and it is also the first route in the navigation stack.
Expected Behavior
When I reopened the app from the background, I don't want to be in the PROFILE screen, but in the HOME screen. I want to reset the first route in navigation stack, changing it with the HOME stack. This would be the same behavior of Instagram (try to go to home -> profile -> home, push the back button two times; now push the back button a third time: the app goes in the background; now reopen Instagram: the app restarts from the home page)
Solution 1:[1]
Maybe too late, but add this in your App:
React.useEffect(() => {
const appStateChangeSub = AppState.addEventListener(
"change",
(nextAppState) => {
if (nextAppState === "active") {
NavigationService.navigate("Home");
}
}
);
return () => {
appStateChangeSub.remove();
};
}, []);
NavigationService -> see doc
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 | Aure77 |
