CodexBloom - Programming Q&A Platform

React Hook Form: Handling Dynamic Fields with Nested Objects Causes Validation Issues

👀 Views: 16 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-14
react react-hook-form validation JavaScript

I'm optimizing some code but I'm prototyping a solution and I'm using React Hook Form v7 to manage a dynamic form where users can add multiple addresses... Each address consists of a street, city, and zip code. I've set up the form using the `useFieldArray` hook to handle the array of addresses, but I'm working with issues with validation when users submit the form. Specifically, the validation is not triggering correctly for nested fields, and I'm getting the behavior message 'want to read property 'street' of undefined'. Here's a simplified version of my code: ```javascript import React from 'react'; import { useForm, useFieldArray } from 'react-hook-form'; const AddressForm = () => { const { register, control, handleSubmit, formState: { errors } } = useForm({ defaultValues: { addresses: [{ street: '', city: '', zip: '' }], }, }); const { fields, append, remove } = useFieldArray({ control, name: 'addresses', }); const onSubmit = (data) => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> {fields.map((item, index) => ( <div key={item.id}> <input {...register(`addresses.${index}.street`, { required: true })} placeholder="Street" /> {errors.addresses?.[index]?.street && <span>This field is required</span>} <input {...register(`addresses.${index}.city`, { required: true })} placeholder="City" /> {errors.addresses?.[index]?.city && <span>This field is required</span>} <input {...register(`addresses.${index}.zip`, { required: true })} placeholder="ZIP" /> {errors.addresses?.[index]?.zip && <span>This field is required</span>} <button type="button" onClick={() => remove(index)}>Remove</button> </div> ))} <button type="button" onClick={() => append({ street: '', city: '', zip: '' })}>Add Address</button> <button type="submit">Submit</button> </form> ); }; export default AddressForm; ``` I've verified that the `register` function correctly maps to the nested fields, but when I try to submit the form with missing required fields, I encounter a situation where the validation sometimes skips over the nested fields entirely, leading to the aforementioned behavior. I've tried adding console logs to check the state of `errors` and `data`, but they don't seem to provide any insight into why the validation fails. Has anyone experienced similar issues with React Hook Form's dynamic fields? What might be the root cause of this validation question, and how can I ensure that the nested fields are validated properly? How would you solve this? I've been using Javascript for about a year now. The project is a web app built with Javascript. Any examples would be super helpful. Cheers for any assistance!