Loading...

React JS Tutorial - #15 Conditional Rendering

9881 57________

We touched on conditional rendering of components in the last video about error handling (   • React JS Tutorial - #14 Error Handling  ). There are three basic ways to render JSX conditionally. One is to use an if/else statement and assign either of the two markup expressions to a variable based on a given condition. Another one is to use a ternary operator: condition ? true : false; you will see this used to conditionally apply the className attribute. Yet another and the shortest one is to write the condition and the JSX expression inline using the logical && (AND) operator. This is also referred to as short-circuit evaluation.

As I alluded previously (   • React JS Tutorial - #13 Input Validation  ), the && operator works differently in JavaScript than in other programming languages. Consider the following condition, boolean && expression. In order for it to be true, as you might expect, both "boolean" and "expression" need to be truthy. If the first operand is falsy (false, 0, ''", null, undefined, NaN), then the statement evaluates to false, and the JS engine will disregard the second operand. In React, this will prevent the second operand from rendering. However, if the first argument is truthy (i.e. NOT falsy), then the expression right after && is returned and evaluated. Within React, this will cause the second element to be rendered.

And with this brief discourse into JavaScript inner workings, let's jump right back in the video. We'll conditionally show a modal component that will display a list of US national holidays between the two dates, as defined in Countdown component. More state management and parent-child component interaction on the way! See you there.

Good read on logical operations in JS www.sitepoint.com/javascript-truthy-falsy

Confused by "falsy" and "truthy"? developer.mozilla.org/en-US/docs/Glossary/Falsy and developer.mozilla.org/en-US/docs/Glossary/Truthy will help.

コメント