React Navigation on tab change
If you are using react-navigation version 5, then you can add tab-press
listener right in your tab screen definition, to do some pre-processing, as mentioned in docs
<Tab.Navigator>
<Tab.Screen
component={HomeScreen}
name="HomeScreen"
listeners={{
tabPress: e => {
if (userIsNotLoggedIn) {
// Prevent default action
e.preventDefault();
navigation.navigate("LoginScreen");
}
},
}}
/>
<Tab.Screen
../>
</Tab.Navigator>
Explanation: When Home
tab will be clicked in BottomBar
, and if user is not logged in, the HomeScreen
won't open and instead LoginScreen
will open(Note: LoginScreen
is navigation name which will be registered some where with a screen). But if user is logged in, then it will behave normally.
Actually, you can add an special listener in your component
componentDidMount () {
this.props.navigation.addListener('willFocus', (route) => { //tab changed });
}
export default () => <MyTabNav
ref={(ref) => { this.nav = ref; }}
onNavigationStateChange={(prevState, currentState) => {
const getCurrentRouteName = (navigationState) => {
if (!navigationState) return null;
const route = navigationState.routes[navigationState.index];
if (route.routes) return getCurrentRouteName(route);
return route.routeName;
};
global.currentRoute = getCurrentRouteName(currentState);
}}
/>;
If you don't want to use redux, this is how you can store global information about the current route, so you can both detect a tab change and also tell which tab is now active.