7

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.

0

2 Answers 2

16

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

2 Comments

In what circumstances does the !! trick result in true, and when will it result in false?
@kojow7 it will convert any falsy value to false (0, null, undefined, "", NaN, false) and anything else to true
1

This happens with react native as with this, actually it checks the string as a value and gives the error.

return <View>
      <Text>Title</Text>>
      {item.mystring ?
               (<View>
                     <Text>Should only be rendered when the mystring property exists and has a value</Text>
               </View>) : null
       }
</View>

You could do something like this to resolve this, or parse it as a boolean first, in your case item.mystring is a string and its inside the render, that too outside text, which makes react-native throw error, it isn't expected, but this has been in react-native since past 2 years :/

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.