loading...

Render Conditionally with a Ternary

chantastic profile image Michael Chan ・1 min read

When you need to render JSX conditionally, you need to use a ternary operator.

There are no if/else statements allowed inside a block of JSX.
Fortunately, JavaScript has us covered.
We can use a ternary operator — a single line expression for conditionals.

The ternary operator looks like this:

someCondition ? doTheTruthyThing() : doTheFalsyThing();

They can be used for assignments.

let activity = happyAndKnowsIt ? "clap hands" : "brood";

And — in JSX — they can be used for conditional rendering.

return (
  <div>
    {pokemon
      ? <Pokemon name={pokemon.name} />
      : <div>couldn't catch 'em all.</div>
    }
  </div>
)

Give it a try

Try you new skills right in the browser.
Go to this sandbox.

Assignment:
Use the Conditional (ternary) operator to render a <Pokemon /> only when we have one to render.

  1. Add a ternary expression. Remember to interpolate it with {} curly braces
  2. If we have a Pokemon to render, render it using the Pokemon Component
  3. If we don't have a Pokemon, show the index for the Pokemon we're missing

Subscribe to all my web developer videos on YouTube:

Follow the 🧵 on Twitter:

Posted on by:

chantastic profile

Michael Chan

@chantastic

Clumsy Jesus follower. Mediocre dev/designer. Pretty OK hubs and dad.

Discussion

pic
Editor guide