Home > Software engineering >  How to navigate to another stack screen from tab navigator in React Native
How to navigate to another stack screen from tab navigator in React Native

Time:09-30

Here is my tab navigator present in MainNavigator.js,

const MainNavigator = () => {
  return (
    <Tab.Navigator>
      <Tab.Screen
        name={'Home'}
        component={Home} />
      <Tab.Screen
        name={'About'}
        component={About} />
      <Tab.Screen
        name={'Profile'}
        component={Profile} />
    </Tab.Navigator>
  ) 

}

I have an AuthNavigator.js which includes a stack navigator,

const AuthNavigator = () => {
  return (
    <Stack.Navigator>
      <Stack.Screen name={'Login'} component={Login} />
      <Stack.Screen name={'Signup'} component={Signup} />
    </Stack.Navigator>
}

So, I have a logout button on my Profile Screen in Tab Navigator. I want to Navigate to Login Screen in AuthNavigator with the onPress event. Here is how I tried this,

const Profile = ({navigation}) => {
  const logoutHandler = () => {
   navigation.navigate('Login');
  }

<SafeAreaView>
  <TouchableOpacity onPress={logoutHandler}>
    <Text>Logout</Text>
  </TouchableOpacity>
</SafeAreaView>
}

However, this is not working. As a beginner to React Native I have no idea how to link this Login route into a Stack screen. Really appreciate it if somebody could save my day. Thankyou so much.

CodePudding user response:

  1. Manage 1 state globally (using redux or some other state management tool) and that is isAuthenticated.

  2. Then in your App.js or where ever you have defined your root navigator do the changes likewise : -

       <NavigationContainer>
           { isAuthenticated ? <AuthRoutes /> : <UnAuthRoute />
       </NavigationContainer>
  1. On login and logout you'll have to update this isAuthenticated state and then routes will be taken care as per the state
  • Related