React Hook Form: How to manage nested form fields dynamically based on user input?
I'm trying to debug I'm integrating two systems and After trying multiple solutions online, I still can't figure this out. Could someone explain I've been struggling with this for a few days now and could really use some help... I'm using React Hook Form (v7) to build a dynamic form where the number of inputs can change based on the user's selection. For instance, if a user selects 'Yes' from a dropdown, I want to render additional input fields for further details. However, I'm running into issues with managing the state of these nested fields. When I try to access the `getValues()` method after dynamically adding fields, it returns an empty object for those fields. Here's a simplified version of my form setup: ```javascript import React from 'react'; import { useForm, Controller } from 'react-hook-form'; const MyForm = () => { const { control, handleSubmit, register, getValues } = useForm(); const [showDetails, setShowDetails] = React.useState(false); const onSubmit = (data) => { console.log(data); }; const handleDropdownChange = (event) => { setShowDetails(event.target.value === 'Yes'); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <label> Select Option: <select onChange={handleDropdownChange}> <option value='No'>No</option> <option value='Yes'>Yes</option> </select> </label> {showDetails && ( <div> <label> Detail 1: <input {...register('details.detail1')} /> </label> <label> Detail 2: <input {...register('details.detail2')} /> </label> </div> )} <button type='submit'>Submit</button> </form> ); }; export default MyForm; ``` When I submit the form, the `data` object only includes values from the default fields, and the nested `details` object is missing altogether. I have tried using `useEffect` to watch the `showDetails` state and re-register the fields, but that didn’t help either. Has anyone tackled a similar issue or can provide insights into properly managing nested dynamic fields with React Hook Form? I'm working on a API that needs to handle this. I'd really appreciate any guidance on this. This is my first time working with Javascript 3.9. What are your experiences with this? Hoping someone can shed some light on this. Am I missing something obvious? Any feedback is welcome!