I am mapping an array of object in react. The array is as follows
const tabs = [
{
index: 0,
title: 'v1',
path: '/v1',
component: versionManager,
},
{
index: 1,
title: 'v2',
path: '/v2',
component: version2Manager,
},
{
index: 0,
title: 'v3',
path: '/v3',
component: version3Manager,
},
];
I have successfully mapped the entire array with this
{tabs.map((item) => {
if (auth.verify(Roles.role1)) {
return (
<Tab
label={item.title}
key={item.index}
component={Link}
to={item.path}
/>
);
but I would like to add an else that only maps the first object (v1) and all of its elements, something similar to this.
} else {
return (
<Tab
label={item.title}
key={item.index}
component={Link}
to={item.path}
/>
)
}
I have tried thing such as item.title[0], item.index[0] ,etc.... but it gives an undefined error every time. Does anyone know the best way to only map the first object in the else statement? Thanks in advance.
I have seen Get first object from array of objects in react but this didn't seem to be helpful in my case.
item.title[0], item.index[0] won't work because item is only an object from the tabs array. What you want is:
} else {
return (
<Tab
label={tabs[0].title}
key={tabs[0].index}
component={Link}
to={tabs[0].path}
/>
)
}
You want to get the first element of the tabs array, but you've been trying to access the first element of the properties of the array as if the properties are arrays themselves, and tabs is just a regular object.
So you'd want to use tabs[0].title, tabs[0].index, etc.
Map always iterates over all of the items of the array. Another way you can try is to first check if the user has the role you need. If not, just return the first tab.
if(auth.verify(Roles.role1)){
return tabs.map((item) => {
return (<Tab
label={item.title}
key={item.index}
component={Link}
to={item.path}
/>);
}
} else {
return (
<Tab
label={tabs[0].title}
key={tabs[0].index}
component={Link}
to={tabs[0].path}
/>)
}