React Native clear text multiple TextInput boxes

Hasen picture Hasen · Nov 22, 2015 · Viewed 7.7k times · Source

I found example code on a facebook React Native page which shows how to use setNativeProp to clear text on a click but I can't see how to do it with multiple text boxes. Here is the code:

var App = React.createClass({
  clearText() {
    this._textInput.setNativeProps({text: ''});
  },

  render() {
    return (
      <View style={styles.container}>
        <TextInput ref={component => this._textInput = component}
               style={styles.textInput} />
        <TouchableOpacity onPress={this.clearText}>
          <Text>Clear text</Text>
        </TouchableOpacity>
      </View>
    );
  }
});

The ref seems to be fixed in the function so will always target the same TextInput box. How can I alter the function to target any TextInput box I indicate?

Answer

eyal83 picture eyal83 · Nov 22, 2015

This should work. Notice that the ref on the TextInput needs to be the one you call from the clearText functino.

var App = React.createClass({
  clearText(fieldName) {
    this.refs[fieldName].setNativeProps({text: ''});
  },

  render() {
    return (
      <View style={styles.container}>
        <TextInput ref={'textInput1'} style={styles.textInput} />
        <TouchableOpacity onPress={() => this.clearText('textInput1')}>
          <Text>Clear text</Text>
        </TouchableOpacity>
        <TextInput ref={'textInput2'} style={styles.textInput} />
        <TouchableOpacity onPress={() => this.clearText('textInput2')}>
          <Text>Clear text</Text>
        </TouchableOpacity>
      </View>
    );
  }
});

Updated my answer to clear different fields.