i am working on react and i want to add diffrent routes like admin and driver. I have two route object for each claims.I am getting user's role from api and i want to showing route by role(claim)
what i have tried,
i added that condition line -> Role==="Admin"? but i got error that Cannot find menuItem what should i do? thanks in advance
const getRole="Admin" //for example
const admin= {
id: 'dashboard',
title: '',
type: 'group',
children: [
{
id: 'default',
title: 'addShipment',
type: 'item',
url: '/dashboard/addShipment',
icon: icons.IconDashboard,
breadcrumbs: false
},
{
id: 'default',
title: 'showShipment',
type: 'item',
url: '/dashboard/showShipment',
icon: icons.IconDashboard,
breadcrumbs: false
}
]
};
const driver= {
id: 'dashboard',
title: '',
type: 'group',
children: [
{
id: 'default',
title: 'showShipment',
type: 'item',
url: '/dashboard/showShipment',
icon: icons.IconDashboard,
breadcrumbs: false
}
]
};
{Role==="Admin"?
(
const menuItem = {
items: [admin]
};
)
:(
const menuItem = {
items: [driver]
};
)
const MenuList = () => {
const navItems = menuItem?.items.map((item) => {
switch (item.type) {
case 'group':
return <NavGroup key={item.id} item={item} />;
default:
return (
<Typography key={item.id} variant="h6" color="error" align="center">
Menu Items Error
</Typography>
);
}
});
return <>{navItems}</>;};
export default MenuList;
CodePudding user response:
This is not the right way to initialize a variable:
{Role==="Admin"?
(
const menuItem = {
items: [admin]
};
)
:(
const menuItem = {
items: [driver]
};
)
}
The variable menuItem
is only present within the scope of that condition.
If you want to use a ternary operator try this:
const menuItem = Role === "Admin" ? { items: [admin] } : { items: [driver] }
OR
const menuItem = { items: [Role === "Admin" ? admin: driver] }