React Hook Form: Conditional Rendering Issues with Nested Forms and Dynamic Fields
I'm writing unit tests and I'm working on a project and hit a roadblock. I'm using React Hook Form (v7) in my project to manage a complex form that involves conditional rendering and nested fields. My main issue arises when I try to render a nested form section based on a parent selection. I've set up a dynamic select input that, when changed, should display additional fields for the user to fill out. However, when I switch the selection back and forth, the previously filled data disappears, and I sometimes see an unexpected validation error stating `"field is required"` even though I have provided a default value. Hereβs a simplified version of my code: ```javascript import React from 'react'; import { useForm, Controller } from 'react-hook-form'; const MyForm = () => { const { control, handleSubmit, watch, setValue } = useForm(); const selectedOption = watch('option'); const onSubmit = (data) => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <Controller name="option" control={control} defaultValue="" render={({ field }) => ( <select {...field}> <option value="">Select an option</option> <option value="option1">Option 1</option> <option value="option2">Option 2</option> </select> )} /> {selectedOption === 'option1' && ( <Controller name="nestedField1" control={control} defaultValue="" rules={{ required: true }} render={({ field }) => <input {...field} placeholder="Nested Field 1" />} /> )} {selectedOption === 'option2' && ( <Controller name="nestedField2" control={control} defaultValue="" rules={{ required: true }} render={({ field }) => <input {...field} placeholder="Nested Field 2" />} /> )} <button type="submit">Submit</button> </form> ); }; export default MyForm; ``` After submitting, if I change the `option` and then change it back, the previously entered data in `nestedField1` or `nestedField2` is lost. I tried using the `setValue` method to keep the data intact based on the selection, but it seems that the form resets. This issue is particularly frustrating because it makes the user experience quite poor. Has anyone else faced this situation? Whatβs the best way to handle such conditional fields without losing data, and how can I prevent the validation errors from interfering when toggling between options? I'm working in a Linux environment. Could someone point me to the right documentation? This is my first time working with Javascript latest.