Hide/Show components in react native

Crysfel picture Crysfel · May 15, 2015 · Viewed 258.3k times · Source

I'm really new to React Native and I'm wondering how can I hide/show a component.
Here's my test case:

<TextInput
    onFocus={this.showCancel()}
    onChangeText={(text) => this.doSearch({input: text})} />

<TouchableHighlight 
    onPress={this.hideCancel()}>
    <View>
        <Text style={styles.cancelButtonText}>Cancel</Text>
    </View>
</TouchableHighlight>

I have a TextInput component, what I want is to show the TouchableHighlight when the input gets the focus, then hide the TouchableHighlight when the user press the cancel button.

I don´t know how to "access" the TouchableHighlight component in order to hide/show it inside of my functions showCancel/hideCancel.
Also, how can I hide the button from the very beginning?

Answer

Krishan Gupta picture Krishan Gupta · Nov 14, 2016

In your render function:

{ this.state.showTheThing && 
  <TextInput/>
}

Then just do:

this.setState({showTheThing: true})  // to show it  
this.setState({showTheThing: false}) // to hide it