L. Swifter
L. Swifter

Reputation: 3237

react native can not use boolean value in component state

I'm using a simple demo to learn react native, I found a strange thing.

This is my code:

export default class App extends Component {

  constructor(props) {
    super(props)
    this.state = {success: false}
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit App.js.
          {this.state.success}        //this line can not be shown
        </Text>
        <Text style={styles.instructions}>
          {instructions}
        </Text>
      </View>
    );
  }
}

I use set a state in the constructor() but can not access it in render(), and when I set the success value to a string or int, it will display.

Is anything wrong in my code ? why can not I use boolean ?

Upvotes: 1

Views: 3394

Answers (1)

Chris
Chris

Reputation: 59511

You are accessing it alright, but nothing is shown because it is a boolean, not a string or number.

If you want to display a literal "true" or "false" you should convert it to a string first with toString():

<Text style={styles.instructions}>
  To get started, edit App.js.
  {this.state.success.toString()}
</Text>

If I remember correctly, I read that they decided not to render boolean values in order to support more flexible in-line conditionals.

Short-circuit evaluation is one such example:

{!this.state.success && <p>Whoops, something went wrong!</p>}

If success is true, the message above won't be rendered. In vanilla JS however, this would return the string literal "false" - not ideal when, like in the example, you want to either render something or nothing.

Imagine how annoying it would be if you rendered the return value of some object method (i.e indexOf(), map(), etc) and react rendered the string literal for undefined, null, and other falsy values. This doesn't happen; instead, React renders nothing.

Some more info from the official documentation here:

false, null, undefined, and true are valid children. They simply don’t render. These JSX expressions will all render to the same thing:

Upvotes: 3

Related Questions