1

I am following a tutorial, this point didn't get explained and got me confused,

What is it to use !isOpen in style?

Does it mean that if I pass isOpen then styles.buttonPadding will work?

export default function ToggleableTimerForm({ isOpen }) {
  return (
    <View style={[styles.container, !isOpen && styles.buttonPadding]}>
      {isOpen ? <TimerForm /> : <TimerButton title="+" color="black" />}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    paddingVertical: 10,
  },
  buttonPadding: {
    paddingHorizontal: 15,
  },
});

2 Answers 2

4

you can use conditionnal test in render to add code and style

with your example :

<View style={[styles.container, !isOpen && styles.buttonPadding]}>
  {isOpen ? <TimerForm /> : <TimerButton title="+" color="black" />}
</View>

if isOpen is true, same as :

<View style={[styles.container, styles.buttonPadding]}>
    <TimerForm />
</View>

if isOpen is false, same as :

<View style={[styles.container]}>
    <TimerButton title="+" color="black" />
</View>

Little off topic, sometimes you can see this syntax :

    <View style={styles.container}>
        {isOpen && <TimerForm />}
    </View>

it is equal to this

    <View style={styles.container}>
        {isOpen ? <TimerForm /> : null}
    </View>
Sign up to request clarification or add additional context in comments.

2 Comments

Had an issue with Typescript complaining, so had to make sure not mixing up ViewStyle vs TextStyle. One question, if we do something like style={ true ? {paddingTop: '50%'} : {}}, will this impact performance with {}?
i think it's ok, it's like doing !isOpen && styles.buttonPadding
1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Short-circuit_evaluation

I think this situation is named short-circuit evaluation. Right side of the && operator applies only when the left side condition is true. In this case, the style will only work when isOpen is false. (Because of !isOpen).

You can use this evaluation for null check. For example, you use users name data from props with {this.props.user.name}, if there is no user data{this.props.user} in props, your app will crash. So, you write {this.props.user && this.props.user.name} and your code will try to access users name data only if there is a user in your props. So, your app won't crash.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.