< Previous: Generating Random Values for Our Page   Next: Using JSX to Render Several Elements at Once >

How to Write if/else Conditional Statements in JSX

Right now our render() code looks like this:

src/pages/Detail.js

return <p>Hello, {chance.first()}!</p>;

Everything inside those braces is ES6 code and will be executed then have its results put back into the render. In this case, it means you'll see random names every time you refresh your page.

However, that code is actually a very specific kind of code called an expression, which very roughly means that it can be translated directly into a value. This is in comparison to another kind of code called a statement, which is where you can for example create variables or perform some other kind of action.

I realize this distinction might seem insignificant, but trust me: it's important. The reason it's important is because you can only use expressions inside JSX braces, not full statements. For example, {this.props.message} and {chance.first()} are both valid, but something like this is not:

{if (chance.first() === 'John') { console.log('Got John');
} else { console.log('Got someone else'); } }

(If you were wondering, === is the recommended way of comparing values in JavaScript; if you use == right now you should probably switch, because there's a big difference between "truth" and "truthy".)

Now, you might very well think "I'm glad that kind of code isn't allowed, because it's so hard to read!" And you'd be right: you can't write if/else statements inside JSX. However, JavaScript is (very loosely) a C-like language, which means it has inherited conditional syntax that lets you do if/else as an expression.

Translated, that means there's a way to rewrite that above statement as an expression, which in turn means you can use it inside JSX. However, you should steel yourself for some pretty grim syntax. Here it is:

src/pages/Detail.js

{chance.first() === 'John' ? console.log('Got John')
: console.log('Got someone else') }

If I write it out on multiple lines it will probably help:

src/pages/Detail.js

{
    chance.first() == 'John'
    ? console.log('Got John')
    : console.log('Got someone else')
}

You can put that into your component if you want to, but it's just an example for demonstration – we'll be removing it shortly.

The opening and closing braces are old, but the bit in the middle is new and is called a ternary expression because it's made up of three parts: the condition (chance.first() == 'John'), what to use if the condition is true (console.log('Got John')) and what to use if the condition is false (console.log('Got someone else')).

The important part is the question mark and the colon: the "true" section comes after the question mark, and the false part comes after the colon. It's not at all obvious, and it really does make for ugly code, but it is absolutely allowable inside JSX and so, like it or not, you'll see ternary expressions all over the place in React code.

Worse, you'll often see double or even triple ternary expressions where the question marks and colons stack up higher and higher to form a true/false tree. These are also allowed by JSX, but I'm pretty sure they are disallowed by the Geneva Convention or something.

One of the few nice things about ternary expressions in JSX is that their result gets put straight into your output. For example:

src/pages/Detail.js

render() {
    return <p>
    {
        chance.first() == 'John'
        ? 'Hello, John!'
        : 'Hello, world!'
    }
    </p>;
}

In that example, the true/false blocks of the ternary expression just contains a string, but that's OK because the string gets passed back into the JSX and will be displayed inside the <p> element.

So: be prepared to use these ternary expressions sometimes, often written entirely on one line, but please remember they are easily abused!

Buy the book for $10

Get the complete, unabridged Hacking with React e-book and take your learning to the next level - includes a 45-day no questions asked money back guarantee!

If this was helpful, please take a moment to tell others about Hacking with React by tweeting about it!

< Previous: Generating Random Values for Our Page   Next: Using JSX to Render Several Elements at Once >

Copyright ©2016 Paul Hudson. Follow me: @twostraws.