React navigation initialRouteName property not working as expected

1.7k Views Asked by At

In my react native app I nested stack navigation inside the tab navigation. I can't access the screen that I set as an initial route in stack navigation.

The tab navigation component is

<Tab.Navigator initialRouteName='HomeNav' >
  <Tab.Screen name="HomeNav" component={HomeNav}
    options={{
      tabBarIcon: ({ color, size }) => (
        <FIcon name="home" color={color} size={size} />
      ),
    }}
  />
  <Tab.Screen name="Search" component={Search}
    options={{
      tabBarIcon: ({ color, size }) => (
        <FIcon name="search" color={color} size={size} />
      )
    }}
  />

  <Tab.Screen name="Cart" component={Cart}
    options={{
      tabBarIcon: ({ color, size }) => (
        <MCIcon2 name="cart" color={color} size={size} />
      )
    }}
  />
  <Tab.Screen name="AccountNav" component={AccountNav}
    options={{
      tabBarIcon: ({ color, size }) => (
        <MCIcon2 name="account" color={color} size={size} />
      )
    }}
  />
</Tab.Navigator >

And here is the account navigation component

const AccountNav = () => {
return (
    <Stack.Navigator
        initialRouteName="Account"
        screenOptions={{
            headerShown: false
        }}
    >
        <Stack.Screen name="Account" component={Account} />
        <Stack.Screen name="MyOrders" component={MyOrders} />
        <Stack.Screen name="Profile" component={Profile} />
    </Stack.Navigator>
);

when I try to navigate to MyOrders screen from the other screens. it gets stuck and cannot access the initial route screen (Account).

1

There are 1 best solutions below

0
On

I had this issue aswell, I solved it by adding lazy: false to the tab navigators screenOptions prop.

screenOptions={{
    headerShown: false,
    lazy: false
  }}

Documentation says that "Routes are lazily initialized -- their screen components are not mounted until they are first focused.", my guess is that the initial route you specify won't "register" until the screen's components are properly mounted (until the screen is focused), so when you go to your AccountNav, the initial route becomes the one you navigated too, bypassing the prop.

The issue with this is that you're mounting all the screen components from all the screens and that may impact performance depending on your application I guess