0

I am evaluating some variables and using the result to conditionally render elements.

This is the evaluation

const condition = this.props.badgeCount > 0

and using the result like this

<View>
  {condition && (
    <View>
      <Text>
        {this.props.badgeCount}
      </Text>
    </View>
  )}
</View>

And RN fails with the error

text strings must be rendered within a text component

and works well when I change condition to

const condition = Boolean(this.props.badgeCount > 0)

So, clearly the results returned back are something like "true" or "false".

My question is why is this, because that is clearly an evaluation that should return a boolean and also is there a way other than the one I am using, to solve this problem?

Siya Mzam
  • 4,655
  • 1
  • 26
  • 44

1 Answers1

2

That is because what you are doing there is an inline if statement. Any string that is not an empty string, null, or undefined is a truthy value (https://developer.mozilla.org/en-US/docs/Glossary/Truthy).

You can easily test this by going in your browser's console and executing:

console.log('someString' ? true : false);
console.log('' ? true : false);

You can solve your problem by doing !!condition which will co-erce the string value to a boolean and thus not trigger the text strings must be rendered within a text component error:

<View>
    {!!condition && (
        <View>
        <Text>
            {this.props.badgeCount}
        </Text>
        </View>
    )}
</View>

More information on !! (NOT NOT) in this answer: https://stackoverflow.com/a/784946/3061857

nbokmans
  • 5,492
  • 4
  • 35
  • 59