React Holiday

Day 11: Use expressions for conditional rendering

You can’t use if/else statements in `render.

render() {
  return (
    <div>{/* no if/else */}</div>
  )
}

In those curly-braces, you can only use expressions. Fortunately, you got a couple options.

Tern or Burn

The ternary operator is a syntax for conditional expressions.

// just like if/else
someCondition ? 'shown if truthy' : 'shown if falsy'

Short circuit

Short-circuit evaluation works too.

someCondition && 'shown only if truthy' // if
someCondition || 'shown only if falsy' // unless

Clap on, clap off, The Clapper

Our ClapCounter (from the 9th) acts like every clap is the first clap.
It just isn’t true.

Let’s use short-circuit evaluation render the message only when there are 0 claps. Let’s also render the number of claps only when there are 1 or more.

<div>
  <button ... >
    {this.state.clapCount >= 0 && this.state.clapCount} 👏
  </button>

  {this.state.clapCount === 0 && <i> be the first to clap</i>}
</div>

Tinker with it

Use the workspace below and explore conditional rendering.

  • Use a ternary to add an alternative message (condition ? truthy : falsy)
  • Get crazy and use what we’ve learned about events and state to conditionally display a message on hover. You can do it!