list
.filter((val) => {
if (
val.name.toLocaleLowerCase().includes(input))
) {
return val
}
})
.map((val, idx) => (
<Li
key={idx}
/>
))
Using this structure, I wanted to do something if returns empty.
Ex: When searching for "abc" and there is no "abc" in the list, a message appears saying that "abc" was not found.
Several things to change:
list
.filter((val) => {
if (
val.name.toLocaleLowerCase().includes(input))
) {
return val
}
})
can be just
list
.filter(val => val.name.toLocaleLowerCase().includes(input)
Remember that the function inside filter
just returns a true
or false
. By chance your expression, which returns the actual list element, is interpreted as true
, and when your expression does not match, you don't return anything, which has the same effect as returning false
. Expressing it as above makes it clearer what you are doing (and is very marginally faster).
const matches = list.filter(val => val.name.toLocaleLowerCase().includes(input)
const output = (matches.length>0) ?
matches.map((val, idx) => (
<Li
key={idx}
/>
)) : (
<div>Not found</div>
)
You can tell if the list is empty using "filter" and "map" by using following JavaScript Code:
list
.filter((value) => (value!==undefined) && (value!==null) && value.name.toLocaleLowerCase().includes(input)))
.map((value, id) => (
<Li
key={id}
/>
))