DEV Community

chantastic
chantastic

Posted on

4 2

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:

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay