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.
- Add a ternary expression. Remember to interpolate it with
{}
curly braces - If we have a Pokemon to render, render it using the Pokemon Component
- 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)