0

Suppose I only want to display h1 element if this.state.display is true.

{this.state.display && <h1>Displayed!</h1> }

works, but

{<h1>Displayed!</h1> && this.state.display}

does not. I am testing it out on here: https://learn.freecodecamp.org/front-end-libraries/react/use-a-ternary-expression-for-conditional-rendering

Anyone know the reason why? Thank you

FranktheTank
  • 292
  • 2
  • 8

1 Answers1

1

&& means "If the left side is truthy, then return the right side. Otherwise (if the left side is falsy), then return the left side." Since <h1>Displayed!</h1> is truthy, that unconditionally evaluates to this.state.display, which isn't what you want to render.