CodexBloom - Programming Q&A Platform

React Hook Form: Conditional Field Rendering with Validation Issues on Submit

๐Ÿ‘€ Views: 38 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-11
react react-hook-form conditional-rendering javascript

This might be a silly question, but I'm working on a form using React Hook Form (version 7.0.0) and I'm facing issues with conditional field rendering based on user selections. I have a dropdown that, when set to 'Yes', should display additional fields that are required for validation, while setting it to 'No' should hide these fields. However, when I submit the form, even though I have conditional logic in place, Iโ€™m getting validation errors for the hidden fields. Hereโ€™s a simplified version of my component: ```javascript import React from 'react'; import { useForm, Controller } from 'react-hook-form'; const MyForm = () => { const { control, handleSubmit, watch, formState: { errors } } = useForm(); const watchCondition = watch('condition'); const onSubmit = data => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <Controller name="condition" control={control} defaultValue="No" render={({ field }) => ( <select {...field}> <option value="No">No</option> <option value="Yes">Yes</option> </select> )} /> {watchCondition === 'Yes' && ( <div> <Controller name="additionalField" control={control} rules={{ required: 'This field is required' }} render={({ field }) => ( <input {...field} placeholder="Additional Field" /> )} /> {errors.additionalField && <p>{errors.additionalField.message}</p>} </div> )} <button type="submit">Submit</button> </form> ); }; ``` Despite adding the `required` rule for `additionalField`, I only see the validation message if I try to submit the form with 'Yes' selected and without filling in the additional input. However, if 'No' is selected, I still get a validation error for `additionalField`. The console log shows the full data object, but the additional field's value is `undefined` when it is not rendered. I've tried using `setValue` to reset the form state but that doesnโ€™t seem to help. Has anyone faced this issue or can suggest a workaround to ensure the validation behaves correctly according to the dynamic rendering of fields? Any ideas what could be causing this? I'm on Debian using the latest version of Javascript. I'd really appreciate any guidance on this.