Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native clear text multiple TextInput boxes

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?

like image 466
Hasen Avatar asked Nov 22 '15 04:11

Hasen


People also ask

How do I delete multiple TextInput in React Native?

var App = React. createClass({ clearText(fieldName) { this. refs[fieldName]. setNativeProps({text: ''}); }, render() { return ( <View style={styles.

How do I clear text in TextInput React Native?

To clear React Native TextInput, we can set the value with a state and clear the state. to set the value prop to val . And we set onChangeText to setVal to set val to the inputted value. Next, we add a Button with the onPress prop set to a function that set val to an empty string with setVal .

How do you Unfocus TextInput React Native?

To unfocus a TextInput in React Native, we can use the Keyboard. dismiss method. to set the onSubmitEditing prop to Keyboard. dismiss .


1 Answers

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.

like image 147
eyal83 Avatar answered Nov 27 '22 02:11

eyal83