Home > Mobile >  Render header right button conditionally with React Navigation in React Native
Render header right button conditionally with React Navigation in React Native

Time:01-17

I am trying to conditionally render the Entypo new-message icon in the right header based on a boolean variable (if the variable is true, then the icon will show up in the header). Please see the minimum reproducible code below. Thanks in advance.

import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import { Ionicons, MaterialCommunityIcons, Entypo } from "@expo/vector-icons";

const Tab = createBottomTabNavigator();

const MainTabNavigator = () => {
return (
    <Tab.Navigator
      initialRouteName="Chats"
      screenOptions={{
        tabBarStyle: { backgroundColor: "whitesmoke" },
        headerStyle: { backgroundColor: "whitesmoke" },
      }}
    >
    <Tab.Screen
        name="Chats"
        component={ChatsScreen}
        options={({ navigation }) => ({
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons
              name="message-processing-outline"
              size={size}
              color={color}
            />
          ),
          headerRight: () => (
            <Entypo
              onPress={() => navigation.navigate("Contacts")}
              name="new-message"
              size={18}
              color={"royalblue"}
              style={{ marginRight: 15 }}
            />
          ),
        })}
      />
    </Tab.Navigator>
);
};

export default MainTabNavigator;

CodePudding user response:

You can do it as below, with a Conditional (ternary) operator. Just replace boleanVariable with your actual variable.

options={({ navigation }) => ({
  tabBarIcon: ({ color, size }) => (
    <MaterialCommunityIcons name="message-processing-outline" size={size} color={color} />
  ),
  headerRight: () =>
    !boleanVariable ? (
      <></>
    ) : (
      <Entypo
        onPress={() => navigation.navigate("Contacts")}
        name="new-message"
        size={18}
        color={"royalblue"}
        style={{ marginRight: 15 }}
      />
    ),
})}
  • Related