I have some react-native code that reads an object. If an object has a particular property I want it to display the code. A minimized code block looks like this:
return <View>
<Text>Title</Text>
{item.mystring &&
<View>
<Text>Should only be rendered when the mystring property exists and has a value</Text>
</View>
}
</View>
It works fine in most cases, however, if the property mystring
does exist but has an empty string I get the following error:
Invariant Violation: Text strings must be rendered within a <Text> component.
Why exactly am I getting this error on an empty string? My preference would be for it to not render the code block.
This trick only works with booleans, null, undefined and 0. React tries to render the string even if it is empty.
You can convert the variable to a boolean:
{!!item.mystring &&
<View>
<Text>Should ...</Text>
</View>
}
Or use the ternary operator
{item.mystring ?
<View>
<Text>Should ...</Text>
</View>
:
null
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With