Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why React Native < Text > component does not show Boolean props?

Tags:

react-native

Using RN standard < Text > component with this code I see "Debug mode: " text only (but expected: "Debug mode: true").

class ClassName extends Component {

  static propTypes = {
    debug: PropTypes.bool
  };

  render() {
    return (
      <View style={...}>
        <Text>Debug mode: {this.props.debug}</Text>
      </View>
    )
  }
}

const mapStateToProps = (state) => {
  console.log(typeof(state.debug); //boolean
  return {
    debug: state.debug
  }
}

export default connect(mapStateToProps)(ClassName);

Screenshot:

enter image description here

As described above "state.debug" is Boolean type:

console.log(typeof(state.debug)); //boolean

The question - why Boolean props does not shown/rendered?

like image 287
Stich Avatar asked Apr 20 '17 21:04

Stich


1 Answers

Because JSX was designed so. According to the React documentation:

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

<div />
<div></div>
<div>{false}</div>
<div>{null}</div>
<div>{undefined}</div>    
<div>{true}</div>

...

Conversely, if you want a value like false, true, null, or undefined to appear in the output, you have to convert it to a string first:

<div>
  My JavaScript variable is {String(myVariable)}.
</div>

So it's not only about React Native. It's how React works.

I'm not sure about the reason for this design decision, but it is handy that false is not rendered for conditional rendering:

{items.length > 0 && <ul>{items.map(item => <li>{item}</li>)}</ul>}

And it makes sense that true is not rendered when false is not rendered.

like image 169
Shuhei Kagawa Avatar answered Nov 28 '22 08:11

Shuhei Kagawa