Dynamic drawer items in React Native

510 Views Asked by At

I need to create a dynamic menu regarding to the logged user.

If the user is not logged in, i only want to show Home and Login.

In case Admin is logged i want to show Home, Orders, Users, My Account and Logout

If the user is logged in i want to show Home, Orders, My Account and Logout

This is my code:

const { Navigator, Screen } = createDrawerNavigator();

const DrawerContent = ({ navigation, state }) => {

  const [user, setUser] = useState();
  const [admin, setAdmin] = useState();
  React.useEffect(() => {
    const loggedIn = async () => { 
      const role = await SecureStore.getItemAsync("role");
      if(role===1)
       setAdmin(true)
     else if(role===2)
       setUser(true)
    }
 }, [])
 

  return(
  <Drawer
    selectedIndex={new IndexPath(state.index)}
    onSelect={index => navigation.navigate(state.routeNames[index.row])>
      <DrawerItem title='Home' />
      {(admin || user)&& (<DrawerItem title='Orders' />)}
      { admin && (<DrawerItem title='Users' />)}
      { admin && user && (<DrawerItem title='My account' />)}
      { !admin && !user && (<DrawerItem title='Login' />)}
      { (admin || user) && (<DrawerItem title='Logout' onPress()=>this.logout/>)}
  </Drawer>
)};
export const DrawerNavigator = () => (
  <Navigator drawerContent={props => <DrawerContent {...props}/>}>
    <Screen name='Home' component={HomeScreen}/>
    <Screen name='Orders' component={OrdersPage}/>
    <Screen name='Users' component={EmployeePage}/>
    <Screen name='My account' component={AccountPage}/>
    <Screen name='Login' component={LoginPage}/>
    <Screen name='Register' component={RegisterPage}/>
    <Screen name='Add User' component={AddUserPage}/>
    <Screen name='Add order' component={CreateOrder}/>
    <Screen name='Order details' component={OrderDetails}/>
  </Navigator>
);

export const AppNavigator = () => (
  <SafeAreaView style={{ flex: 1 }}>
    <NavigationContainer>
      <DrawerNavigator/>
    </NavigationContainer>
  </SafeAreaView>
);

I was using UI kittens library. Please let me know if you have any suggestions on how to fix it. I've been struggling with this for days

1

There are 1 best solutions below

0
Alija Fajic On

It is easier for you to make 2 separate drawers, one for the user and one for the actor, and then show it to them regarding their role.