Reputation: 802
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,
},
});
Upvotes: 1
Views: 670
Reputation: 4728
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>
Upvotes: 4
Reputation: 71
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.
Upvotes: 1