CodexBloom - Programming Q&A Platform

React Hook Form: How to handle dynamic fields with validation without losing state?

๐Ÿ‘€ Views: 0 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-16
react react-hook-form javascript JavaScript

Quick question that's been bugging me - I'm trying to figure out I'm sure I'm missing something obvious here, but I'm using React Hook Form (v7) to manage a dynamic form where users can add or remove address fields..... The question is when I add new fields dynamically, the validation doesn't seem to apply correctly, and I lose the state of the already filled fields. I have implemented the form using `useFieldArray` but I keep running into issues where, upon removing a field, the entire form resets or throws a 'Field value want to be null' behavior. Hereโ€™s a concise version of my implementation: ```javascript import React from 'react'; import { useForm, useFieldArray } from 'react-hook-form'; const AddressForm = () => { const { register, control, handleSubmit } = useForm({ defaultValues: { addresses: [{ street: '', city: '' }] } }); const { fields, append, remove } = useFieldArray({ control, name: 'addresses' }); const onSubmit = data => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> {fields.map((field, index) => ( <div key={field.id}> <input {...register(`addresses.${index}.street`, { required: true })} placeholder="Street" /> <input {...register(`addresses.${index}.city`, { required: true })} placeholder="City" /> <button type="button" onClick={() => remove(index)}>Remove</button> </div> ))} <button type="button" onClick={() => append({ street: '', city: '' })}>Add Address</button> <input type="submit" /> </form> ); }; export default AddressForm; ``` I've tried ensuring that the `defaultValues` are set correctly on each render, but it doesnโ€™t seem to help. Also, I read that using `key={field.id}` is critical for React's reconciliation process, but the issues continue regardless. Can anyone provide insight into maintaining the state and validation correctly in this kind of dynamic form setup? For context: I'm using Javascript on macOS. I'd really appreciate any guidance on this. I'd be grateful for any help. The project is a mobile app built with Javascript. What's the correct way to implement this?