Reputation: 2351
I am looking at a repo that has a render statement with a conditional that has actual components as logical conditions.
return <Component>
{
this.state.loading == true &&
<ActivityIndicator
animating={this.state.loading}
/> ||
<View>
...
</View>
}
</Component>
I am interpreting it as, 'if state is loading' AND this call to reactDOM.render() returns something OR this call to reacDOM.render() returns something, then...
but the THEN is getting me. Then what?
Is this some sort of ternary? What are the curly brackets inside of Component
? Where is the result of the condition specified?
Upvotes: 0
Views: 1487
Reputation: 16354
This is called Short-circuit evaluation.
It's a language feature of javascript. When chaining expressions with &&
and ||
it will be always the last value returned, that is evaluated. Python does the same with and
and or
operators. Some other languages like e.g. PHP always return a boolean value.
In fact that means:
expr1 && expr2
Returns
expr1
if it can be converted to false; otherwise, returnsexpr2
. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
expr1 || expr2
Returns
expr1
if it can be converted to true; otherwise, returnsexpr2
. Thus, when used with Boolean values, || returns true if either operand is true.
Furthermore the &&
has precedence over ||
which means that a || b && c
is equivalent to a || (b && c)
.
Your example just chains two of these together leading to: "If this.state.loading
is truthy return <ActivityIndicator>
else return <View>
". This abuses the fact, that null
, undefined
, true
and false
are valid nodes that do not actually render anything for conditional rendering.
Upvotes: 2