Search code examples
javascriptreactjsecmascript-6es6-map

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

Solution

  • With a ternary operator:

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