React: How to show message when result is zero in

2019-07-19 03:40发布

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>
        );
    }
}

3条回答
欢心
2楼-- · 2019-07-19 04:09

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>
查看更多
Melony?
3楼-- · 2019-07-19 04:11
{offersList.length ? (
    // html markup with results
) : (
    // html markup if no results
)}
查看更多
够拽才男人
4楼-- · 2019-07-19 04:14

With a ternary operator:

<main>
   <div className="container">
     <h1>Main {offersList.length}</h1>
     { offersList.length ? offersList : <p>No result</p> }
   </div>
 </main>
查看更多
登录 后发表回答