Conditionally render JSX in React with ternary and logical operators

Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

In this lesson, we decide what markup should be rendered with ternary and logical operators inside our JSX. We want to control the shortlist title, and if there are no names in the ShortList, we don't want to render an empty <ul> tag in the DOM!

Simon Vrachliotis: [0:00] Small detail, our shortlist component is outputting the ul element to the DOM regardless of whether there actually are any items in the shortlist. We should avoid doing that. A quick way to fix this is to create a variable called hasNames, which will check if the length of the shortlisted names array is greater than zero.

[0:19] JSX allows us to use logical operators in ternaries for conditional outputs. Let's do two things here. First, let's add a heading tag that will display a different title based on the hasNames variable. If hasNames is true, the heading will say, "Your shortlist." Otherwise, it will prompt user to "Click on a name to shortlist it."

[0:44] Now, let's wrap the NameList component in a hasNames with && operator. That will only render the NameList if hasNames is true.

[0:55] I also want to add a horizontal rule separator below. We need to fragment here to have a single top-level element. I'll import Fragment from React at the top and wrap my NameList in hr here in the Fragment.

[1:12] Here we go! It's working.

egghead
egghead
~ 34 seconds ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today