Khaled Boussoffara
Khaled Boussoffara

Reputation: 1771

what's ref in react native and when should i use ref?

I'm working on react native project, i created forms with react native components. I used TextInput to edit a state value like this :

<TextInput
    shake
    keyboardAppearance='light'
    autoFocus={false}
    autoCapitalize='none'
    autoCorrect={false}
    keyboardType='default'
    returnKeyType='next'
    value={this.state.sector}
    onChangeText={sector => this.setState({ sector })}
/>

With console.log the sector value i get correctly the current value after input change, but i have seen some examples with ref like this :

<TextInput
    shake
    keyboardAppearance='light'
    autoFocus={false}
    autoCapitalize='none'
    autoCorrect={false}
    keyboardType='default'
    returnKeyType='next'
    value={this.state.sector}
    ref={input => (this.sectorInput = input)}
    onChangeText={sector => this.setState({ sector })}
/>

i don't understand this operation :

ref={input => (this.sectorInput = input)}

can someone explain what's the ref and why we used with an input and when should i use a ref ?

Upvotes: 0

Views: 676

Answers (1)

Kishan Bharda
Kishan Bharda

Reputation: 5700

If you want to access TextInput methods then you have to create reference of that component, then using reference you can use it's method.

For example you have form in your app and you want that when user fill the first field and after that you want to set focus on next field then you can do like this :

<TextInput
    shake
    keyboardAppearance='light'
    autoFocus={false}
    autoCapitalize='none'
    autoCorrect={false}
    keyboardType='default'
    returnKeyType='next'
    value={this.state.sector}
    ref={input => { this.sectorInput = input}}
    onSubmitEditing={() => {
        this.nextField.focus();
    }}
    onChangeText={sector => this.setState({ sector })}
/>

<TextInput
    shake
    keyboardAppearance='light'
    autoFocus={false}
    autoCapitalize='none'
    autoCorrect={false}
    keyboardType='default'
    returnKeyType='next'
    value={this.state.sector}
    ref={input => { this.nextField = input}}
    onSubmitEditing={() => {
        this.handleSubmit();
    }}
    onChangeText={nextField => this.setState({ nextField })}
/>

Now, when user will fill the sector field then if he press next, then nextField will automatically get focused.

Upvotes: 2

Related Questions