The conditional render is a subtle and powerful secret tool used by modern Javascript developers.
To understand why it is so subtle and powerful, let’s review JSX syntax basis:
- • You are working in what looks like Javascript, except things that are HTML-like, get turned into their corresponding React or HTML components
2. When inside of an XHTML block, you can then re-escape back into Javascript using {
and }
3. The opening and closing braces must contain a complete Javascript expression, which will get evaluated and output into the markup. It cannot contain an if statement, or another kind of Javascript block structure.
4. Within the escaped { and }, we can also use string interpolation which themselves can contain {
and }
. (This last point we will see in the example below makes JSX even more powerful than people realize.)
If you’re coming from another language that uses mark-templates, point #3 is often lost: You can’t do if / else statements inside of JSX like you can with other markup template syntaxes. That’s because of JSX’s sneaky and powerful parsing that lets you seamlessly move between JS logic and markup.
{ if (my_condition) { }
<div>Hello world!</div>
{ } }
Does not work!
The final thing to know here is that — in basically all programming languages — and statements along with evaluation & print (which is what happens pretty much any time you tell something to be written to the screen) do something interesting:
• If the first operand returns false, they will stop evaluating and return nothing.
• If the first operand returns true, they will continue evaluating to the next operand.
• Finally, when they exit, they will not concatenate the values of the IF condition (that would be strange), instead it will return the final value.
JSX developers have used this to create a handy alternative to having proper IF / ELSE statements in our syntax: the conditional render:
{ someCondition && "Hello world" }
Remember, someCondition should simply be truthy or falsy, it doesn’t actually get output to the screen. What gets output to the screen is “Hello world”
This is used very frequently in React code to display messages that show up under, unsurprisingly, some conditions that are props or state on the React component.