admin管理员组

文章数量:1391836

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

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>
        );
    }
}
Share Improve this question asked Jul 20, 2017 at 21:12 Mo.Mo. 27.6k36 gold badges166 silver badges233 bronze badges 1
  • 1 If offersList.length === 0 show No results. else show the list. – Matt Commented Jul 20, 2017 at 21:13
Add a ment  | 

3 Answers 3

Reset to default 4

With a ternary operator:

<main>
   <div className="container">
     <h1>Main {offersList.length}</h1>
     { offersList.length ? offersList : <p>No result</p> }
   </div>
 </main>

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>
{offersList.length ? (
    // html markup with results
) : (
    // html markup if no results
)}

本文标签: javascriptReact How to show message when result is zero in reactStack Overflow