简体   繁体   中英

React conditional statement within a map function

I am displaying reviews from the Google Maps API. Within my map function I only want to display reviews that are higher than a 1 rating. How can I update my map function to only display reviews where review.rating > 1 ?

{this.state.reviews && this.state.reviews.map((review, index) => (
    <div key={index} className="review">
        <p>{review.text}</p>
    </div>
))}

Just filter them before map:

{this.state.reviews
    .filter((review) => review.rating > 1) // get only reviews with rating > 1
    .map((review, index) => (
       <div key={index} className="review">
          <p>{review.text}</p>
       </div>
    ))
}

If, for some reason you don't want to call the .filter method on the array, you could do something like this. Basically you are calling a ternary operator in your return. Let me know if you need any more explanation.

 {this.state.reviews && this.state.reviews.map((review, index) => ( review.index > 1 ? (<div key={index} className="review"> <p>{review.text}</p> </div>) : null ))}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM