7

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?

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

4 Comments

But your onPress has no values? How would you distinguish it from another onPress to clear a different textinput? You'd still need to create two separate functions. Can you show an example with two textinputs and two touchableopacity buttons to demonstrate how it would work with just the one function?
Ok looks like its along the right lines but doesn't actually work. Did it work at your end?
You have to do it like this this.refs[fieldName].setNativeProps({text: ''}); and then it works. Thanks :)
Yup, had a typo in there. Updated my answer.
1

You can also use something like this to clear the text of TextInput.

clearText(fieldName) {
  this.refs[fieldName].clear(0);
},

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.