I'm getting an array in React/Next, but before mapping through it I'm running a few filters and sorting it. I'd like to display a simple message if nothing gets found after the filters run. It should display a span with a simple text string (jsx).
The code is pretty simple:
{ArrayObj
.filter(
(item) =>
// conditions here
)
.sort((a, b) => (a.condition > b.condition ? 1 : -1))
.map((item) => (
<li key={item._id}>
// contents of each iteration here
</li>
))}
I'm guessing it should go just right before the .map but I'm stuck at this.
The full code is as follows:
{yachtListings
.filter(
(yacht) =>
yacht.buildYear >= searchYear &&
yacht.price <= searchPrice &&
yacht.length <= searchLength &&
yacht.type === searchType
)
.filter((yacht) =>
filterKeyword == ''
? yacht
: yacht.modelName
.toLowerCase()
.includes(filterKeyword.toLowerCase())
)
.sort((a, b) => (a[sortOrder] > b[sortOrder] ? 1 : -1))
.map((yacht) => (
<li key={yacht._id}>
<SecondHandCard /> // card components with props
</li>
))}
You can see a live demo here. I'm a front-end guy taking my skills to the back-end more and more.
You could filter the array first and then conditionally show jsx depending on the length of that.
let filteredArray = ArrayObj.filter((item) => {...}).sort(...);
{filteredArray.length == 0 ? <span>Message</span> : filteredArray.map(...)}