Reputation: 335
In ReactNative, I have a property that might or might not be passed down to a class object. Is there a way like in Java to check to see the property is null or not?
In my case, I have this.props.overrideAccessibilityLabel that might be passed down or not. I only want to use it when it is passed down:
render() {
return (
<View
accessibilityLabel={this.props.currMessage.text}
if {...props.myAccessibilityLabel} {
...accessibilityLabel={...props.myAccessibilityLabel}
}
>
<Text1
// ...
>
</Text1>
</View>
);
}
Upvotes: 2
Views: 721
Reputation: 555
But then a one-liner "if" statement works the best in this case.
<View
accessibilityLabel={this.props.currMessage.text ?
this.props.currMessage.text : this. props.myAccessibilityLabel}
>
<Text1
// ...
>
</Text1>
</View>
Upvotes: 4
Reputation: 131
In ReactNative, when a property is not present, it is evaluated to false. (An empty string is also evaluated to false.) So using "if" to check whether a property is present is the right way to do.
function myFunc(x) {
if (x) {
return true;
} else {
return false;
}
}
var a1 = {}
a1.a = "abc"
a1.b = ""
var ra=myFunc(a1.a)
var rb=myFunc(a1.b)
var rc=myFunc(a1.b)
console.log("ra=" + ra + "; rb=" + rb + "; rc=" + rc)
The output is:
ra=true; rb=false; rc=false
So a property is treated differently from a var. Checking an empty property just results in false, whereby referencing a undefined var causes an exception.
Upvotes: 3