简体   繁体   中英

Render header right button conditionally with React Navigation in React Native

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;

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 }}
      />
    ),
})}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM