2

How to show No Result message when the search result is empty with in map() ?

export class Properties extends React.Component {
    render () {
        const { data, searchText } = this.props;
        const offersList = data
            .filter(offerDetail => {
                return offerDetail.city.toLowerCase().indexOf(searchText.toLowerCase()) >= 0;
            })
            .map(offerDetail => {
                return (
                    <div className="offer" key={offerDetail.id}>
                        <h2 className="offer-title">{offerDetail.title}</h2>
                        <p className="offer-location"><i className="location-icon"></i> {offerDetail.city}</p>
                    </div>
                );
            });
        return (
            <main>
                <div className="container">
                    <h1>Main {offersList.length}</h1>
                    { offersList }
                </div>
            </main>
        );
    }
}
Mo.
  • 26,306
  • 36
  • 159
  • 225

3 Answers3

4

With a ternary operator:

<main>
   <div className="container">
     <h1>Main {offersList.length}</h1>
     { offersList.length ? offersList : <p>No result</p> }
   </div>
 </main>
Eelke
  • 2,267
  • 1
  • 22
  • 26
3

If offersList array is empty, it's length will equal to 0. You can make easy condition:

<div className="container">
  <h1>Main {offersList.length}</h1>
  { offersList.length ? offersList : <p>No Result</p> }
</div>
kind user
  • 40,029
  • 7
  • 67
  • 77
0
{offersList.length ? (
    // html markup with results
) : (
    // html markup if no results
)}
Christopher
  • 592
  • 9
  • 31