kojow7
kojow7

Reputation: 11394

Using conditional rendering with empty strings

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.

Upvotes: 7

Views: 12531

Answers (2)

sney2002
sney2002

Reputation: 896

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
}

Upvotes: 16

Sarmad Shah
Sarmad Shah

Reputation: 3805

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 :/

Upvotes: 1

Related Questions