Evanss
Evanss

Reputation: 23593

Render some text if array.filter returns 0 in React?

I have a filter on an array in the render function in a React component:

someArray.filter(item => {
    if (item.name.includes(searchText))return true
}).map(item=>{
    return <h1>{item.name}</h1> 
});

How can I elegantly display some text along the lines of "No search results" when no items are being returned by the map function?

Upvotes: 0

Views: 1780

Answers (3)

Liren Yeo
Liren Yeo

Reputation: 3451

Short and concise:

someArray.map(({name}) => name.includes(searchText) && <h1>{name}</h1>)

Upvotes: 0

Mayank Shukla
Mayank Shukla

Reputation: 104379

One possible way is, instead of putting this code directly inside JSX render method, put it inside a method and call that method from render.

Like this:

_filterItem(){
    const arr = someArray.filter(item => item.name.includes(searchText))

    if(!arr.length) return <div>No data found</div>;

    return arr.map(item => <h1 key={/*some unique value*/}>{item.name}</h1>)
}


render(){
    return(
        <div>{this._filterItem()}</div>
    )
}

Suggestion:

With filter and map you can use concise body of arrow function instead of block body, for more details check MDN Doc.

Upvotes: 0

Andrew Li
Andrew Li

Reputation: 57964

There are a few ways you can do this. You can use a ternary operator (and also shorten your callbacks):

const filtered = someArray.filter(item => 
  item.name.includes(searchText)
);

//Then, in your JSX:
{
  filtered.length > 0 ?
    filtered.map((item, key) => 
      <h1 key={key}>{item.name}</h1>
    )
  :
    <h1>No search results</h1>
}

This checks if there are any filtered results. If so, it will map them to h1s that have the name of the item. If not, then it will simply render a single h1 with the text 'No search results'.

Upvotes: 3

Related Questions