How to Write if/else Conditional Statements in JSX

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 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:

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: