chlkdst
chlkdst

Reputation: 197

Style concatenation using conditional styles

Could you elaborate this expression written in React

<View style={[styles.button, this.state.touching && styles.highlight]} />

I know that Style attribute accepts an array of objects, what wonders me is the this.state.touching && styles.highlight part. Can someone enlighten me on how this works? Many thanks!

Upvotes: 0

Views: 347

Answers (1)

Ori Drori
Ori Drori

Reputation: 191976

This is a logical if using And (&&). If the first value is false, it will return that value, if it's truthy, it will return the 2nd value.

const state = {
  touching: false
};

const styles = {
  highlight: 'highlightClass'
};

console.log('state.touching is false: ', state.touching && styles.highlight);

state.touching = true;

console.log('state.touching is true: ',state.touching && styles.highlight);

Note that that there won't be a style of false if it's falsey, because react native styles ignore falsy values. According to the docs:

The behavior is the same as Object.assign: in case of conflicting values, the one from the right-most element will have precedence and falsy values like false, undefined and null will be ignored. A common pattern is to conditionally add a style based on some condition.

Upvotes: 3

Related Questions