I started studying NextJs a few weeks ago and I'm having difficulty extracting a value using map from a list where one of the items has multiple values to a specific key.
I am trying to create a RBAC menu. If the role have just one value, everything works fine. However, when I try to add multiple values I am not able to make it work.
My array:
export const links = [
{
name: 'TIMETRACKER',
href: '/dashboard/timetracker',
icon: ClockIcon,
role: 'user',
},
{
name: 'MANAGE',
href: '#',
icon: HomeIcon,
role: ['manager', 'admin'],
},
{
name: 'SETTINGS',
href: '#',
icon: HomeIcon,
role: ['user', 'manager', 'admin'],
},
]
The first one works as a charm, but the other ones just doesn't works.
My validation function is inside a map and try to validate every item of this map:
{links?.map((link, indexItem) => {
const LinkIcon = link.icon;
return (
<div key={indexItem} className="mt-2 md:mt-0">
{!link.subitems && (link.role === userrole || link.role === '') ? (
<ul>
<li className="mr-2 inline-block md:mr-0 md:list-item">
<Link
key={link.name}
href={link.href}
className={clsx(
'flex h-[48px] grow items-center justify-center gap-2 rounded-md bg-gray-50 p-3 text-sm font-medium hover:bg-sky-100 hover:text-blue-600 md:flex-none md:justify-start md:p-2 md:px-3',
{ 'bg-sky-100 text-black': pathname === link.href },
)}
>
<LinkIcon className="w-6" />
<p className="hidden md:block">{link.name}</p>
</Link>
</li>
</ul>
) : null }
</div>
);
})}
Should I create another Map to validate the permission instead?
You need to modify your link.role
equality check to iterate over a list for the second and third configs.
e.g. instead of
{!link.subitems && (link.role === userrole || link.role === '') ? (
change it to
{!link.subitems && (Array.isArray(link.role)
? link.role.includes(userrole)
: link.role === userrole || link.role === '') ? (