Search code examples
javascriptreact-nativereact-navigationreact-navigation-v5

React Navigation V5 InitalRouteName not working with conditional rendering


I'd like to take the user to the profile page if their information doesn't exist yet. But the initialRouteName isn't working when using conditional rendering with the jwt. Maybe i'm missing a better approach. Does anyone have any suggestions?

function ExploreNavigator() {
  const jwt = useSelector(state => state.session.jwt);
  const { firstName } = useSelector(state => state.user);

  return (
    <Stack.Navigator
      headerMode="screen"
      initialRouteName={firstName ? "Listings" : "Profile"}
      screenOptions={{
        cardStyle: {
          backgroundColor: 'white',
        },
      }}>
      {jwt ? (
        <>
          <Stack.Screen
            name="Listings"
            component={ListingsScreen}
            options={{ title: 'My Studios' }}
          />

          <Stack.Screen
            name="Onboarding"
            component={OnboardingScreen}
            options={{
              headerShown: false,
            }}
          />
          <Stack.Screen
            name="Profile"
            component={ProfileScreen}
            options={{
              headerShown: false,
            }}
          />
        </>
      ) : (
        <>
          <Stack.Screen
            name="Sign Up"
            component={SignUpScreen}
            options={{
              headerShown: false,
            }}
          />
          <Stack.Screen
            name="Login"
            component={LoginScreen}
            options={{
              headerShown: false,
            }}
          />
        </>
      )}
    </Stack.Navigator>
  );
}


Solution

  • You have an error in your code

    initialRouteName={firstName? "Listings": "Profile"} if you look closely, there's no space between firstName and the question mark operator. The code should look like this

    initialRouteName={firstName ? "Listings" : "Profile"}