If you started working with React-native and you are already familiar with React, you might assume that if you navigate to route A to B, component B will mount and component A will unmount (componentWillUnmount will be called). But it doesn’t work like that. Although React navigation is supported in React Native, it doesn't work in the same way as in React.
In React native when you navigate to route A, component A will mount. When you navigate to route B from route A, component B will mount but component A will not unmount. It will remain mounted in the stack navigator, so when you again navigate to route A, you will notice no changes in component A.
Nesting navigators mean rendering a navigator inside a screen of another navigator.
Consider the following example of nested navigators
function Home() {
return (
<Stack.Navigator>
<Stack.Screen name="Home" component={Home} />
<Stack.Screen name="Flights" component={Flights} />
<Stack.Screen name="Hotels" component={Hotels} />
<Stack.Screen name="Events" component={Events} />
</Stack.Navigator>
)
}
function App() {
return (
<NavigationContainer>
<Tab.Navigator>
<Tab.Screen name="Home" component={Home} />
<Tab.Screen name="Trips" component={Trips} />
<Tab.Screen name="Settings" component={Settings} />
</Tab.Navigator>
</NavigationContainer>
)
}
Each navigator keeps its history and nested navigators do not listen to parent’s events.
Like in the above example, there is a stack navigator inside the tab navigator. The screens in stack navigator won't listen to the parent's events i.e. tab navigator events. To listen to the parent’s events we have to explicitly trigger a tabPress event on tab navigator.
function App() {
return (
<NavigationContainer>
<Tab.Navigator>
<Tab.Screen name="Home" component={Home}
listeners={({ navigation }) => ({
tabPress: (event) => {
e.preventDefault();
navigation.navigate(“Home”, {screen: “home” };
}
})}
/>
<Tab.Screen name="Trips" component={Trips} />
<Tab.Screen name="Settings" component={Settings} />
</Tab.Navigator>
</NavigationContainer>
);
}
For a better understanding of nested navigator refer to react-navigation docs
Happy Coding !!! 🙂
Rupinder Kaur