user13286
user13286

Reputation: 3075

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

Upvotes: 0

Views: 62

Answers (2)

Jhecht
Jhecht

Reputation: 4435

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

Upvotes: 3

kind user
kind user

Reputation: 41893

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

Upvotes: 6

Related Questions