2

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>
    );
  }
1

2 Answers 2

4

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>
Sign up to request clarification or add additional context in comments.

Comments

3

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.

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.