Reputation: 87
I have list item which shows some data what I want to do is if array length greater than 10 I wanna get first 10 element of subzonemenus.ItemList then map if and add end of li one more 1 li element so total li element will be 11. but if subzonemenus.ItemList array length is not greater than 10 than return how many li it has and last li will not be added. I hope I am clear
<div className="row">
{megamenu != null && megamenu.list.map((subzonemenus, idx) => (
<div className="col" key={idx}>
<Link to={`${process.env.PUBLIC_URL}/abcde`} className="nolink">{subzonemenus.Title}</Link>
<ul className="submenu">
{
subzonemenus.ItemList.lenght > 10 ?
//get first 10 element of subzonemenus.ItemList then map it so if length > 10 will show only first 10 element of array
subzonemenus.ItemList != null && subzonemenus.ItemList.map((menuItemlist, idx) => (
<li key={idx}><Link to={menuItemlist.Path}>{menuItemlist.MenuItemText}</Link></li>
))
// if length greater than 10 then will add end of li this li to "show all"
<li key={idx}><Link to={menuItemlist.Path}>{menuItemlist.ShowAll}</Link></li>
// else length is not greater than 10 then last li will not be added
:
subzonemenus.ItemList != null && subzonemenus.ItemList.map((menuItemlist, idx) => (
<li key={idx}><Link to={menuItemlist.Path}>{menuItemlist.MenuItemText}</Link></li>
))
}
</ul>
</div>
))}
</div>
Upvotes: 0
Views: 2532
Reputation: 3900
Please check this, I have tried to answer this based on my understanding.
Looks like your code requires some modification. Like you need not explicitly check != null
, because if a variable is null it will evaluate to false and the and operation will return false without moving further.
I have moved the logic related to li to a new method renderItems
You can slice(0,10) the array to get first 10 elements, for less elements, it will return all the elements.
Then a ternary for 'show all', if length greater than 10 the show all will be added else nothing.
const renderItems = (itemList) => {
let list = itemList.slice(0,10).map((menuItemlist, idx) => (
<li key={idx}><Link to={menuItemlist.Path}>{menuItemlist.MenuItemText}</Link></li>
)) ;
if(itemList.length > 10)
list.push(<li key={10}><Link to={itemList[10].Path}>{itemList[10].ShowAll}</Link></li>);
return list;
}
{megamenu && megamenu.list
&& megamenu.list.map((subzonemenus, idx) => (
<div className="col" key={idx}>
<Link to={`${process.env.PUBLIC_URL}/abcde`} className="nolink">{subzonemenus.Title}</Link>
<ul className="submenu">
{
subzonemenus.ItemList && renderItems(subzonemenus.ItemList);
}
</ul>
</div>
))}
Upvotes: 1
Reputation: 327
You have a typo here:
subzonemenus.ItemList.lenght > 10 ?
change the .lenght
to .length
Upvotes: 1