Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 332
kojow7 Avatar asked Dec 13 '22 09:12

kojow7


1 Answers

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
}
like image 125
sney2002 Avatar answered Dec 20 '22 18:12

sney2002