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?