5
votes

React Native using React Navigation - Show/Hide Drawer Item

I was wondering if you guys or maybe someone have come up of a better Idea of showing or hiding some menu or Drawer Item under DrawerNavigator.

Basically I have user roles and I want to show/hide selected menu's based on user's role.

My setup now is that I have A DrawerNavigator nested within a StackNavigator.

Menu That Contains My Drawer Items

Hide some drawer items based on user role

Currently Using:

react version 16.0.0-alpha.12

react-native version 0.46.0

react-navigation version 1.0.0-beta.11

1
Welcome to SO, please read the help section on how to ask questionsStudioTime
@DarrenSweeney Thank You for the advice :)deejaygeroso

1 Answers

4
votes

You can create your own custom component that will be rendering drawer items

contentComponent: CustomDrawerContentComponent

inside that component you can define logic on show hide your items

example:

const CustomItems = ({
  navigation: { state, navigate },
  items,
  activeItemKey,
  activeTintColor,
  activeBackgroundColor,
  inactiveTintColor,
  inactiveBackgroundColor,
  getLabel,
  renderIcon,
  onItemPress,
  style,
  labelStyle,
}: Props) => (
  <View style={[styles.container, style]}>
    {items.map((route: NavigationRoute, index: number) => {
      const focused = activeItemKey === route.key;
      const color = focused ? activeTintColor : inactiveTintColor;
      const backgroundColor = focused
        ? activeBackgroundColor
        : inactiveBackgroundColor;
      const scene = { route, index, focused, tintColor: color };
      const icon = renderIcon(scene);
      const label = getLabel(scene);
      return (
        <TouchableOpacity
          key={route.key}
          onPress={() => {
            console.log('pressed')
            onItemPress({ route, focused });
          }}
          delayPressIn={0}
        >
          <View style={[styles.item, { backgroundColor }]}>
            {icon ? (
              <View style={[styles.icon, focused ? null : styles.inactiveIcon]}>
                {icon}
              </View>
            ) : null}
            {typeof label === 'string' ? (
              <Text style={[styles.label, { color }, labelStyle]}>{label}</Text>
            ) : (
              label
            )}
          </View>
        </TouchableOpacity>
      );
    })}
  </View>
);

So in the code above you can define which route will be shown, for instance you can have store with list of items show or hide and from here you can make comparison.

Hope it helps