1

I'm using the conditional operator to determine whether an extra element should be included in my React component. For some reason if product.rating is 0 I see it rendered after the name. If I typecast the value to bool like Boolean(product.rating) the 0 is gone. My question is why the 0 is rendered at the first place, shouldn't the falsy value evaluate the condition as false?

function Product ({product}) {
  return (
    <div>
      <h1>{product.name}</h1>
      {product.rating && (
        <Stars count={product.rating} />
      )}
    </div>
  )
}
Laszlo
  • 2,225
  • 19
  • 22
  • 2
    `a && b` evaluates to `a` if `!a`, `b` otherwise, so `0 && …` is `0`. – Ry- Dec 06 '17 at 12:20
  • I agree that this is a duplicate, but I think more ppl going to have the same question about react's conditional rendering approach since it's part of the doc and this question gives better context for particular case. – Laszlo Dec 13 '17 at 18:51

0 Answers0