Conditionally render JSX in React with ternary and logical operators

Share this video with your friends

Social Share Links

Send Tweet

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.