Home > Back-end >  How do I add public screens to react-navigation
How do I add public screens to react-navigation

Time:01-02

I am building a react-native app using Expo and react-navigation, the app currently has two navigators, one is visible to authenticated users and one is only visible to unauthenticated users, like the sign-in page.

Here is the navigation structure:

function Navigation({ isLoggedIn }) {
  return (
    <NavigationContainer>
      {isLoggedIn ? (
        <Stack.Navigator>
          <Stack.Screen name="home" component={Home}></Stack.Screen>
          <Stack.Screen name="public" component={Public}></Stack.Screen>
        </Stack.Navigator>
      ) : (
        <Stack.Navigator>
          <Stack.Screen name="login" component={Login}></Stack.Screen>
          <Stack.Screen name="public" component={Public}></Stack.Screen>
        </Stack.Navigator>
      )}
    </NavigationContainer>
  );
}

as you can see there is a screen called 'public' that appears twice in both navigators because I want people to be able to view this component regardless of their authentication status, is this the correct way to do it?

CodePudding user response:

Instead of initiating two separate Stack Navigator based on isLoggedIn state, what you can do is initiating one Stack Navigator and then put screens based on isLoggedIn state. Like the following

      <NavigationContainer>
        <Stack.Navigator>
          
          {isLoggedIn ? (
            <Stack.Screen name="home" component={Home}></Stack.Screen>
          ) : (
            <Stack.Screen name="login" component={Login}></Stack.Screen>
          )}
          
          <Stack.Screen name="public" component={Public}></Stack.Screen>
        </Stack.Navigator>
      </NavigationContainer>
    

In this way, you don't have to put the 'public' screen twice but users can see that screen regardless of their authentication status. Also, you don't have to initiate StackNavigator twice.

  • Related