React ๐ŸŽ„

๐ŸŽ‰ Now on video! ๐Ÿ“บ
Buy, buy, buy!!!

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.

  <button ... >
    {this.state.clapCount >= 0 && this.state.clapCount} ๐Ÿ‘

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

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!
โ† Previous
Next โ†’

Learn other React stuff...