Stack Overflow
Stack Overflow

Reputation: 2968

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 !!!

Upvotes: 3

Views: 1718

Answers (1)

Sami Hult
Sami Hult

Reputation: 3082

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?)

Upvotes: 8

Related Questions