SaurabhG
SaurabhG

Reputation: 193

React Native - Shift focus to next Input box upon pressing "Next" button in keyboard

I am very new in react Native world. I want to shift focus from the first input box to second input box. Please find my below code.

<View style={styles.inputViewStyle}>
                  <TextInput
                    ref={firstnameRef => (this.firstnameRef = 
                    firstnameRef)}
                    label="Firstname"
                    returnKeyType="next"
                    autoCorrect={false}
                    value={this.state.firstname}
                    onSubmitEditing={() => 
              this.refs.middlenameRef.focus()}
                    onChangeText={firstname => this.setState({ firstname })}
                    blurOnSubmit={false}
                  />
                </View> 

    <View style={styles.inputViewStyle}>
                  <TextInput
                    ref={middlenameRef => (this.middlenameRef = middlenameRef)}
                    label="Middlename"
                    returnKeyType="go"
                    value={this.state.middlename}
                    onChangeText={middlename => this.setState({ middlename })}
                  />
                </View>

I am getting error -> "undefined is not an object(evaluating 'this2.middlenameRef.focus()')"

UPDATE: constructor(props) { super(props); this.state = { firstname: "", middlename: "", lastname: ""
};

Please guide. Thanks in advance.

Upvotes: 0

Views: 1413

Answers (4)

<TextInput
    placeholder = "FirstTextInput"
    returnKeyType = { "next" }
    onSubmitEditing={() => { this.secondTextInput.focus(); }}
    blurOnSubmit={false}
/>
<TextInput
    ref={(input) => { this.secondTextInput = input; }}
    placeholder = "secondTextInput"
/>

Upvotes: 1

Jeff Gu Kang
Jeff Gu Kang

Reputation: 4879

You can get instance directly through this. And null Checking could be a good option for debug.

onSubmitEditing={() => this.middlenameRef && this.middlenameRef.focus()}

Upvotes: 0

Set the second TextInput focus, when the previous TextInput's onSubmitEditing is triggered.

Try this

  1. Adding a Ref to second TextInput ref={(input) => { this.secondTextInput = input; }}

  2. Bind focus function to first TextInput's onSubmitEditing event. onSubmitEditing={() => { this.secondTextInput.focus(); }}

  3. Remember to set blurOnSubmit to false, to prevent keyboard flickering. blurOnSubmit={false}

Upvotes: 2

Uzair A.
Uzair A.

Reputation: 1638

Try this:

onSubmitEditing={() => { this.middlenameRef.focus() }}

Upvotes: 0

Related Questions