Search
⌘K
    to navigateEnterto select Escto close

    Navigation best practices

    Use constants for screen names

    Always use constants for screen names instead of using hard-coded values. For example, here for each Stack.Screen we have their names defined in a constant screenNames.

    1const screenNames = {
    2  Home: "Home",
    3  Profile: "Profile",
    4};
    5return (
    6  <NavigationContainer>
    7    <Stack.Navigator>
    8      <Stack.Screen name={screenNames.Home} component={HomeScreen} />
    9      <Stack.Screen name={screenNames.Profile} component={ProfileScreen} />
    10    </Stack.Navigator>
    11  </NavigationContainer>
    12);

    Setting tab bar icons

    Custom Bottom Tab Icons can be added from the BottomTab.Navigator instead of each BottomTab.Screen to avoid code duplication.

    For example, here we have assigned an Icon to every BottomTab.Screen individually.

    1return (
    2  <BottomTab.Navigator>
    3    <BottomTab.Screen
    4      options={{
    5        tabBarIcon: () => <Icon name="ticket-line" />,
    6      }}
    7      name="HelpDesk"
    8      component={TicketsIndexScreen}
    9    />
    10    <BottomTab.Screen
    11      options={{
    12        tabBarIcon: () => <Icon name="chat-3-line" />,
    13      }}
    14      name="ChatScreen"
    15      component={ChatConversationScreen}
    16    />
    17    <BottomTab.Screen
    18      options={{
    19        tabBarIcon: () => <Icon name="notification-4-line" />,
    20      }}
    21      name="Notification"
    22      component={NotificationScreen}
    23    />
    24    <BottomTab.Screen
    25      options={{
    26        tabBarIcon: () => <Icon name="user-3-line" />,
    27      }}
    28      name="ProfileScreen"
    29      component={ProfileScreen}
    30    />
    31  </BottomTab.Navigator>
    32);

    But here, we create an object with the Icon labels and assign them to the screens based on the route.name from the BottomTab.Navigator itself.

    1const BottomNavAssetNames = {
    2  TicketScreen: { icon: "ticket-line" },
    3  ChatScreen: { icon: "chat-3-line" },
    4  NotificationScreen: { icon: "notification-4-line" },
    5  ProfileScreen: { icon: "user-3-line" },
    6};
    7
    8return (
    9  <BottomTab.Navigator
    10    screenOptions={({ route }) => ({
    11      tabBarIcon: ({ color, size, focused }) => (
    12        <Icon name={BottomNavAssetNames[route.name].icon} />
    13      ),
    14    })}
    15  >
    16    <BottomTab.Screen name="TicketScreen" component={TicketsIndexScreen} />
    17    <BottomTab.Screen name="ChatScreen" component={ChatConversationScreen} />
    18    <BottomTab.Screen
    19      name="NotificationScreen"
    20      component={NotificationScreen}
    21    />
    22    <BottomTab.Screen name="ProfileScreen" component={ProfileScreen} />
    23  </BottomTab.Navigator>
    24);
    Previous
    Next