Search code examples
reactjsreact-nativeshort-circuiting

View control through boolean short-circuiting


I came across an example like this when I was learning React Native:

class Example extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showView: true,
    }
  }

  removeView(){
     this.setState({
       showView: false,
     });
  }

  render(){
    return (
       <View style={{flex: 1, alignItems: 'center', justifyContent: 'center' }}>
       {this.state.showView && (
            <View style={{backgroundColor: 'red', height: 100, width: 100 }}> // View to be removed
                <TouchableHighlight onPress={() => this.removeView()}>
                  <Text>Remove View</Text>
                </TouchableHighlight>
            </View>
       )}
       </View>
    )
  }
}

What I don't understand is why the View can be controlled by this.state.showView this way, I'm sure it definitely has to do with boolean short-circuiting, but I think the content in the brackets should evaluate to a boolean value, so I should only be able to a true/false value on the component instead of seeing the content of the View. Can somebody explain a bit more about why it works?


Solution

  • According to React documentation:

    It works because in JavaScript, true && expression always evaluates to expression, and false && expression always evaluates to false.

    Therefore, if the condition is true, the element right after && will appear in the output. If it is false, React will ignore and skip it.