Mo.
Mo.

Reputation: 27543

React: How to show message when result is zero in react

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

Upvotes: 2

Views: 3354

Answers (3)

Christopher
Christopher

Reputation: 620

{offersList.length ? (
    // html markup with results
) : (
    // html markup if no results
)}

Upvotes: 0

kind user
kind user

Reputation: 41913

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>

Upvotes: 3

Eelke
Eelke

Reputation: 2327

With a ternary operator:

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

Upvotes: 4

Related Questions