Please explain the logic behind 12. JSX conditionals &&

Hello.

So I understand &&. I’ve used it many times. It is the AND conditional. However here, I don’t understand at all how it is being used. I don’t understand why an HTML statement is being used in the condition or what value is being assigned to the judgemental variable.

var React = require('react');
var ReactDOM = require('react-dom');

// judgmental will be true half the time.
var judgmental = Math.random() < 0.5;

var favoriteFoods = (
  <div>
    <h1>My Favorite Foods</h1>
    <ul>
      <li>Sushi Burrito</li>
      <li>Rhubarb Pie</li>
      { !judgmental && <li>Nacho Cheez Straight Out The Jar</li> }
      <li>Broiled Grapefruit</li>
    </ul>
  </div>
);

ReactDOM.render(
	favoriteFoods, 
	document.getElementById('app')
);

This will produce a boolean, which as the comment describes, will be true roughly half the time.

When it is true, the JSX will render (it is a truthy object). When it is false, the expression is false since true && false is false, so the JSX will not render.

Remember, the expression is JavaScript and JSX, so needs to be treated as program code, not markup.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.