2

I have a requirement to make a multi-level drawer menu for an app using React Native. I can customize the drawer by using a CustomDrawerContent. Within this i want to display a subset of the routes. Currently i am making a copy of the props and changing the state.routes variable within it. Is there a better way of doing this?

const Drawer = createDrawerNavigator();
function CustomDrawerContent(props) {  
  const prop2 = props;
  prop2.state.routes = prop2.state.routes.slice(0, 3);

  return (
    <DrawerContentScrollView {...props} contentContainerStyle={{ flex: 1 }}>
        <View style={styles.drawerMenu}>
            <DrawerItemList {...prop2} />
        </View>
    </DrawerContentScrollView>
  );
}

export default function () {
  return (
    <Drawer.Navigator initialRouteName="Home_Home" hideStatusBar={true} statusBarAnimation="fade" 
        drawerContent={(props) => <CustomDrawerContent {...props} />}>
      <Drawer.Screen name="Home_Home" component={HomeStack} />
      <Drawer.Screen name="Home_About" component={HomeStack} />
      <Drawer.Screen name="Home_FAQ" component={HomeStack} />
      <Drawer.Screen name="Profile_Calendar" component={HomeStack} />
      <Drawer.Screen name="Profile_Subscription" component={HomeStack} />
    </Drawer.Navigator>
  );
}

I have tried passing in state as a props but that doesnt seem to pick it up.

Shubham
  • 329
  • 1
  • 5
  • 17

1 Answers1

2

You can replace the DrawerItemList with the actual code from the react-navigation repository and then filter out the routes you want/ don't want like this:

  const buildLink = useLinkBuilder()

  // Add your logic here
  const visibleRoutes = ['home', 'profile', 'resources', 'faq']
  
  const drawerList = props.state.routes.map((route: any, i: number) => {
    const focused = i === props.state.index
    const { title, drawerLabel, drawerIcon } = props.descriptors[route.key].options

    if (!visibleRoutes.includes(route.name)) {
      return <View key={route.key} />
    }

    return (
      <DrawerItem
        key={route.key}
        label={
          drawerLabel !== undefined
            ? drawerLabel
            : title !== undefined
            ? title
            : route.name
        }
        icon={drawerIcon}
        focused={focused}
        activeTintColor={props.activeTintColor}
        inactiveTintColor={props.inactiveTintColor}
        activeBackgroundColor={props.activeBackgroundColor}
        inactiveBackgroundColor={props.inactiveBackgroundColor}
        labelStyle={props.labelStyle}
        style={props.itemStyle}
        to={buildLink(route.name, route.params)}
        onPress={() => {
          props.navigation.dispatch({
            ...(focused
              ? DrawerActions.closeDrawer()
              : CommonActions.navigate(route.name)),
            target: props.state.key,
          })
        }}
      />
    )
  })
Stefanos Chrs
  • 2,228
  • 3
  • 19
  • 46