In JavaScript ES6 there are different methods to simplify working with Arrays, like filter
, map
, reduce
, sort
, …
Also nullish values can easily be escaped with the ??
syntax.
However, empty arrays are not considered as nullish.
I often want to display a list of items, and in case there is no item in the list I would want to display a placeholder like “There are no items in this list”.
I could do this by doing something like this:
return (
mylist.length ?
mylist.map(item => (
<div key={item.id)>{item.title}</div>
)
) : <div>There are no items in this list</div>
);
However, if I also filter my list, things get more complicated:
return (
mylist.filter(item => myComplexNestedFilter).length ?
mylist.filter(item => myComplexNestedFilter).map(item => (
<div key={item.id)>{item.title}</div>
)
) : <div>There are no items in this list</div>
);
Which could be worked around by saving the filtered list into a const
variable but sometimes, this makes readability quite a bit harder.
So I was wondering if there’s something like:
mylist.filter(item => myComplexNestedFilter).map(item => (
<div key={item.id)>{item.title}</div>
) ?? <div>There are no items in this list</div>
or:
mylist.filter(item => myComplexNestedFilter).map(item => (
<div key={item.id)>{item.title}</div>
).empty(<div>There are no items in this list</div>)
or some other pretty solution for this? I am pretty sure I am not the only one facing this.