5

I am trying to utilize dynamic fields with react-hook-form in react native. I initially tried to manually register everything, but that doesn't work. Then I tried to use the useFieldArray hook, but all the newly created fields don't register correctly. Here is my latest approach:

I have a custom component to mimic the web interface for a react native TextInput and forward the ref.

const Input = forwardRef((props, ref) => {
  const {
    onAdd,
    ...inputProps
  } = props

  return (
    <View>
      <TextInput
       ref={ref}
       {...inputProps} />
      <Button onPress=(() => onAdd()} />
    </View>
  )
}

I then use this component according to how the useFieldArray docs show in my form except that I have a custom change handler. I also set the ref explicitly and attempt to register the individual new field.

const Inputs = useRef([])
const { control, register, setValue, handleSubmit, errors } = useForm({
  defaultValues: {
    test: defaultVals // this is an array of objects {title: '', id: ''}
  }
})

{
  fields.map((field, idx, arr) => (
    <Input 
      key={field.id}
      name={`test[${idx}]`}
      defaultValue={field.name}
      onChangeText={text => handleInput(text, idx)}
      onAdd={() => append({title: '', id: ''})
      ref={ 
        e => register({ name: `test[${idx}]` 
        Inputs.curent[idx] = e
      })
}

When I click the button for the input it renders a new input as would be expected. But when I submit the data, I only get the defaultVals values and not the data from the new input, though I do have an object that represents that input in the test array. It seems something is off with the registering of the inputs, but I can't put my finger on it.

How do I properly set up useFieldArray or utilize other ways to have dynamic fields in react native with react-hook-form?

2
  • have you tried with wrapper your input with Controller? Commented May 23, 2020 at 1:36
  • here is an example with Controller: codesandbox.io/s/react-hook-form-usefieldarray-vy8fv i think you can wrapper with RN component as well Commented May 23, 2020 at 1:37

1 Answer 1

0

you can try handle this problem like me, use each element with 1 input and field like this

 <Controller
      control={control}
      name="username"
      rules={{
        required: {value: true, message: '* Please enter your username *'},
        minLength: {value: 5, message: '* Account should be 5-20 characters in length! *'},
        maxLength: {value: 20, message: '* Account should be 5-20 characters in length! *'},
        pattern: {value: new RegExp(/^[a-zA-Z0-9_-]*$/), message: '* Invalid character *'},
      }}
      render={({onChange, value}) => (
        <InputRegular
          placeholder="username"
          icon={{
            default: images.iconUser,
            focus: images.iconUser2,
          }}
          onChangeText={(val: string) => {
            onChange(val);
            setValue('username', val);
          }}
          value={value}
        />
      )}
    />

handleSubmit with

const {register, errors, setValue, getValues, control, handleSubmit} = useForm<FormData>({
    defaultValues: {
      username: null,
      email: null,
      password: null,
      rePassword: null,
    },
    mode: 'all',
  });

  useEffect(() => {
    register('username');
    register('email');
    register('password');
    register('rePassword');
  }, [register]);
  const onSubmit = async (data: any) => {
    console.log('====================================');
    console.log('data', data);
    console.log('====================================');
    if (getValues('username')) {
      dispatch(
        actionGetRegister({
          data: {
            username: getValues('username'),
            email: getValues('email'),
            password: getValues('password'),
            secondaryPassword: getValues('secondaryPassword'),
          },
        }),
      );
    }
  };

> 

you can see my post for detail i use react-hook-form for react native

https://medium.com/@hoanghuychh/how-to-use-react-hook-form-with-react-native-integrate-validate-and-more-via-typescript-signup-244b7cce895b
Sign up to request clarification or add additional context in comments.

1 Comment

where does this answer address useFieldArray option ?

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.