I'm trying to create a dynamic form using react-hook-form's useFieldArray
hook. The user should be able to add or remove fields, thus making it dynamic. I've looked at this tutorial for inspiration, but the missing piece is how to implement error validation to the state, which will be an array of objects: {email: string}[]
. (The object will take more key/value pairs. I've left out the rest for simplicity.)
I've tried using yup
as validation schema. It looks like this:
const schema = yup.array().of(
yup.object().shape({
email: yup.string().email().required(),
}),
)
The implementation into react-hook-form is:
import * as yup from 'yup'
import { yupResolver } from '@hookform/resolvers/yup'
import { useForm, useFieldArray, Controller } from 'react-hook-form'
const { register, control, handleSubmit, errors } = useForm({
resolver: yupResolver(schema),
mode: 'onChange',
})
const { fields, append, remove } = useFieldArray({
control,
name: 'users',
})
The form is more or less according to the tutorial in the link above.
When console logging the error
object from useForm
hook it is consistently giving an empty object {}
. It doesn't seem like it works. I am probably missing something here. The question is what?