Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - Why using the && operator in array?

I am learning to StyleSheet api and found the following expression in this documentation:

<Text style={[styles.title, this.props.isActive && styles.activeTitle]} />

Can anyone tell what is this && operator used for inside the array? A little example will be more appreciated. Thanks !!!

like image 294
Stack Overflow Avatar asked May 12 '26 12:05

Stack Overflow


1 Answers

This form takes advantage of operator short circuiting.

If this.props.isActive yields true, then the value of this.props.isActive && styles.activeTitle will be styles.activeTitle.

In the opposite case, if this.props.isActive is "falsy" (coerced to false in boolean context), the expression will short-circuit and yield this.props.isActive.

The style parameter in React Native can take an array of style objects that are merged. A false value will be skipped*, so if !isActive, then the style parameter will simply become styles.title.

(*Merge is probably done using Object.assign which will copy only enumerable and own properties, and will not throw on falsy values; but I don't know this for sure. Does someone?)

like image 102
Sami Hult Avatar answered May 14 '26 01:05

Sami Hult



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!