Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Native Base Input Refs Not Being Set

So I'm working with the Native Base <Input> tag, trying to set refs to handle "tabbing" through form fields. I've got the following code:

<Item floatingLabel>
  <Label style={{ color: "#fff" }}>First Name</Label>
  <Input
    ref={input => {
      this.firstNameRef = input;
    }}
    onSubmitEditing={() => {
      this.lastNameRef._root.focus();
    }}
    returnKeyType={"next"}
  />
</Item>

<Item floatingLabel last>
  <Label style={{ color: "#fff" }}>Last Name</Label>
  <Input
    ref={input => {
      this.lastNameRef = input;
    }}
  />
</Item>

So essentially, I have 2 <Input> tags, both with ref set (this.firstNameRef and this.lastNameRef), but on loading the App, pressing First Name, then pressing "next" on the keyboard I get the following error:

Cannot read property '_root' of undefined
onSubmitEditing
Signup.js:162:26

It seems that using <Input> doesn't actually set any ref values, so this.lastNameRef is null.

I also tried using React Native's <TextInput> element, which does handle setting refs as described above, but still doesn't seem to handle focus after submit (even when removing ._root from .focus() logic).

Has anyone else seen this issue?

Note: Only tested in iOS currently.

like image 508
Tim Lewis Avatar asked Sep 26 '18 17:09

Tim Lewis


1 Answers

An update to the accepted answer: ref and getRef both work, but only one will work depeneding on the wrapping component. In this case, my <Input> components are wrapped by an <Item> component, each with different label properties. Compare:

<Item floatingLabel>
  <Label>First Name</Label>
  <Input
    getRef={input => {
      this.firstNameRef = input;
    }}
    onSubmitEditing={() => {
      this.lastNameRef._root.focus();
    }}
    returnKeyType={"next"}
  />
</Item>

And

<Item fixedLabel>
  <Label>First Name</Label>
  <Input
    ref={input => {
      this.lastNameRef = input;
    }}
    onSubmitEditing={() => {
      this.lastNameRef._root.focus();
    }}
    returnKeyType={"next"}
  />
</Item>

In the case of floatingLabel, getRef works, while ref does not. On the other hand, in the case of fixedLabel, ref works, while getRef does not.

Not really to explain why, but maybe this caveat will help someone else in the future.

like image 185
Tim Lewis Avatar answered Sep 19 '22 20:09

Tim Lewis