Abhishek Nalin
Abhishek Nalin

Reputation: 4597

undefined exception while calling focus method on TextInput ref

I am trying to implement the solution proposed here for setting the focus on the next TextInput. The solution is proposed for iOS but I think it should also work for Android.

However I am getting the following exception:

undefined is not a function (evaluating '_this3.refs.Second.focus()')

I am using this Floating Label as my Text Input component. Here is my code:

  <FloatingLabel
            label='First'
            ref='First'
            validationRegex={/[A-Za-z0-9 ]+/}
            value={this.props.First}
            style={commonStyles.formInput}
            onSubmitEditing={(event) => {this.refs.Second.focus()}}
              onChangeText={(text) => this.onUpdate('First', text)}>
              First</FloatingLabel>

  <FloatingLabel
            label='Second'
            ref='Second'
            style={commonStyles.formInput}
            value={this.props.Second}
            validationRegex={/(^([a-zA-Z]{5})([0-9]{4})([a-zA-Z]{1})$)/}
            onChangeText={(text) => this.onUpdate('Second', text)}>
          Second</FloatingLabel>

Can somebody help me in solving the exception? (RN 0.29, Android)

onSubmitEditing={(event) => {console.log(this.refs.Second)}} //works fine

Why am I unable to call the focus method?

Upvotes: 0

Views: 1903

Answers (1)

Saleel
Saleel

Reputation: 899

this.refs.Second is a FloatingLabel object which don't have a method named "focus".

You can add a focus function to FloatingLabel component like below:

focus() {
    this.refs.textInput.focus();
},

and add a ref to the TextInput in render

<View style={elementStyles}>
    {this._renderLabel()}
    <TextInput
      ref={'textInput'}
      {...props}
    >
    </TextInput>
</View>

Upvotes: 5

Related Questions