Isaac
Isaac

Reputation: 12884

Problem with conditional rendering in React Native using falsey value

<Item stackedLabel disabled>
  <Label style={{ color: 'black' }}>{someLabel}</Label>
    {
      0 &&
      <Input style={{ color: 'grey' }} value={this.props.someprop} disabled />
    }
</Item>

I've created a snack, to demo that we can use falsey value for conditional rendering. However, the above code throwing me error

Invariant Violation: Text strings must be rendered within a component

However, if we replace 0 with null/false then it's working fine?

Upvotes: 1

Views: 258

Answers (2)

vonovak
vonovak

Reputation: 1597

I've created a snack, to demo that we can use falsey value for conditional rendering.

And the snack fails, so it's actually not the case.

Expanding on Saeed's answer, the code snippet is an equivalent of

<Item stackedLabel disabled>
  <Label style={{ color: 'black' }}>{someLabel}</Label>
  0
</Item>

React Native does not know what to do with the zero and hence prints the error.

Upvotes: 1

Saeed
Saeed

Reputation: 2279

That is because React sees that 0 as a string.

Simply convert it to a boolean with this trick:

!!(anything not boolean)

// this is equal to false
!!(0)

Upvotes: 0

Related Questions