DEV Community

chantastic
chantastic

Posted on

Render Conditionally with a Ternary

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(); 
Enter fullscreen mode Exit fullscreen mode

They can be used for assignments.

let activity = happyAndKnowsIt ? "clap hands" : "brood"; 
Enter fullscreen mode Exit fullscreen mode

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> ) 
Enter fullscreen mode Exit fullscreen mode

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:

Top comments (0)