How to Use Ternary Operators in JSX Code to Implement Conditional Behavior
Now that you have an introduction to the syntax and the process for implementing conditionals in React, we're going to take that knowledge and we're going to extend it a little further.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

We're going to be able to reinforce what we've learned and we're also going to learn a different way of implementing conditionals inside of a React application. Now we are going to take a little break from the portfolio container component and we're going to create a navigation component. So if I go to app.js, and remember that is located at the root of our components directory.

If I click on app, I'm going to start to add this entire navigation component. So we haven't created it yet. So I'm going to come up here at the top and I'm just going to start typing as if our component was already created. So, I'm gonna say navigation container and we're not passing any prompts into it.

So now let's go up here and let's import it. So I'm going to say instead of portfolio, this is going to say navigation container, and then it's not going to be inside a portfolio, we're going to create a new directory called navigation and then we'll call this navigation-container. So right now we'll get an error because we don't actually have any of these items.

So let's go and let's start creating those. So if you open up the file directory, I'm going to close portfolio and click new folder and just type navigation, inside of navigation, let's create a new file called navigation-container.js and that is all we're going to need, let's now create our component. Now, because this component is going to have to have conditionals and it's going to have to have some data and some state and there's really no need to use a functional component in this case so we can go straight into working with a class based component.

So one thing I would highly recommend right now is for you to pause the video and have a little practice creating a class component again, you already have an example in earlier from the course with the portfolio container component. So I'd say let's pause the video right now and try to create it, you don't have to implement the conditional functionality or anything like that, but it is good to do that and I'll see you back here when you finish it.

So if you did do that, good job, if not, if you ran into any problems, don't worry, I'm going to build it for us right now. So I'm going to say import and then we want to import React and then component and we want to bring that in from React and then from there I want to export default and this is going to be a class and we're going to call this navigation component which extends component, not components, component.

I'm going to add a constructor function because I know I'm going to have to use it eventually anyway. Make sure we call super and we don't have to set any state or anything right now, so this is more of a placeholder than anything else. Then remember that, every class component needs to have a render function which is going to return some JSX, so this is going to return some data and let's see, what do we want it to return?

We're just going to test this out, so I'm going to give it a div. Let's give a className and actually we haven't gotten to class names yet so I'm sorry, I kind of skipped ahead to the way I'd usually do it, but we're not going to get into class names until later on in the course. So let's just add a few items and it's fine if you didn't do this when you were building it out. But I want to add some buttons up here and so we'll have one for home and then let's do one for about and then let's do contact and blog, let's do one more for add blog.

navigation-container.js

import React, { Component } from 'react';

export default class NavigationComponent extends Component {
    constructor() {
        super();
    }

    render() {
        return (
            <div>
            <button>Home</button>
            <button>About</button>
            <button>Contact</button>
            <button>Blog</button>
            <button>Add Blog</button>
            </div>
        )
    }
}

So each one of these items, these first four items, those are going to be links we want everyone to see. This add blog is one that we should only see if the admin, which in your case will be you, is accessing the site. So we built out our full class component, so now this should be working, assuming I don't have any typos or anything. So let's go here and there we go, that is all working. So we have home, we have about, contact, blog and add blog.

large

If you're going through this and you think, "Wow, this is the ugliest site I've ever seen," you're 100% right. We haven't added a single style in this entire application and that's a normal process. It's very rare that I start adding styles right away because I first want to build some of the core features of the application. And if you take any application in the world, if you take Facebook, you take Twitter, Google, any of those, at one point in that product's life cycle, they look like this.

It was just pure HTML and the browser was just rendering that and it didn't have any kind of style. So don't worry, our portfolio will look much better than this. But for right now this is giving us exactly what we're looking for. So now that we have each one of these items, let's imagine that we have a user who comes to the page and they're just a regular user wanting to look at your portfolio.

They should see the home link, about, contact and blog, but they shouldn't see this, only you should see this add blog link. So how are we going to fix this? Well, there are a couple ways of implementing conditionals and we already walked through one, where we just have that quick return statement and there's another way we could do this. We could come up here and we could create a custom function, so I could say something like adminLinks just like this, and then inside of adminLinks I could map over a list of links and say if there's a user signed in or an admin user signed in, then I want you to render all of these links and that's perfectly fine and that's definitely one way of doing it.

But that's probably not going to be the best option. The approach I see the very most in professional React applications is to use what is called the ternary operator. So let's switch to the browser really quick and open up a JavaScript console session here, and let's just walk through this, this is pure vanilla JavaScript and so this is going to help us understand what a ternary operator is because this is a process that I have heard a lot of complaints from students on because it looks very weird.

If you're used to regular conditionals, like saying something like if asdf is triple equal to asdf then I want you to return, yay, just like this, and obviously I need to end my curly brackets, but that's a normal conditional. Well, what a ternary operator is, is it allows you to implement a conditional on a single line. So what I can do with the ternary operator is say something like this.

I could say asdf and then triples equals asdf, just like that, just like a regular condition and then add a question mark. So what I'm doing is I'm setting up a standard if else conditional, so I'm saying if this first, what's on the left, is equal to what's on the right, then I want you to perform this task. So if that's true, then I'm going to say yay. If it's not, I'm going to add a colon and I'm going to say nay, and you can see that that automatically returns yay.

large

If I come back here and say is not equal to, you can see that returns nay.

large

That is what a ternary operator is, I know they're confusing, I have gotten so many complaints on people, especially students who have never seen them before and they think that they're ridiculous to use just because it is much easier and it's much more intuitive to read a standard if else type conditional. But when we're using JSX, that common convention is to actually use a ternary operator.

So I'd definitely start practicing in using them because you're going to see a lot of them. Even if you don't personally want to use them, you're going to see them in many tutorials and so the more familiar you can be with them, the easier it's going to be for actually building out your programs. So let's close this and let's go switch back to the code and see how we can do this.

So right now we have this add blog button. Now we don't have a way of checking to see if a user is signed in yet, we have a whole section on authorization and that's going to be further down in the course. So for right now we're just going to have to hard code this value in. So what I'm going to do is I'm going to treat this like regular JavaScript.

So I'm gonna use the single curly bracket and I'm just going to say true. So this is going to be the scenario where you are signed in and once we get to this part in the application build, we will create a function that will return back if a user is an admin or not, so it will return either true or false, so we're replicating that. The cool thing is later on we're actually going to be able to simply slide that function directly in to this call here. So instead of it saying true or false, then we will call it, but we're not going to have to change any other part of the program.

So I'm going to say if that is true, so if the user has signed in. Then I want you to return this button that says add blog. Now, if not, then in that case, I'm just going to return an empty string. I could also put null, there's a bunch of different things I could do, I essentially just want it to be empty. So if I end the curly brackets, so everything that we just did here is exactly what we did in the console.

We set up a conditional, then we put a question mark, then we put what we want to return, if that conditional is true, and then we gave what the else condition was, which is I want it to be null. So if you save that and now switch back to the browser, you can see it still says add blog. Now if you come over here and we'll imagine that an admin is not logged in and say false, hit save and come back and now you can see that that button is gone.

large

So that is working perfectly and you will see as you start building out React applications and reading tutorials, you're going to see this convention followed quite a bit because it's a way of putting a conditional directly into JSX and being able to have that type of dynamic behavior.

One other item before we leave this section is you notice here where I'm saying button and you may be curious why do we have a button here and it's because we're going to in our routing section, which is one we're going to be doing right after this, in the routing section, we're going to be able to pull all of that out. We're not going to use regular links like you usually would do with a navigation bar. Instead, we're going to use special React router links and so these buttons here are just placeholders, they're eventually going to be replaced with components, link components actually, and so that's what we're going to have after this.

But hopefully that's starting to make sense. You've seen two key ways that you are able to implement conditionals in your React applications, the first one being where you actually have a short circuit render call, which, I'll open up portfolio container, so the first process is to short circuit the render call and have it return something early like a loading status.

// short circuit
render() {
    if (this.state.isLoading) {
        return <div>Loading...</div>;
    }

Then the next way is by implementing ternary operators directly into the JSX code.

// ternary operator
{false ? <button>Add Blog</button> : null}

Resources