I have FirstName and LastName input Fields. I have a read only field called FullName which will have value based on FirstName and LastName. What ever is typed in the first name and last name input fields the Fullname will be Firstname + LastName. I am trying with below code however when i type the second field the first field value becomes undefined and full name ends up being undefined Smith
const F_Name = watch("FirstName", false);
const L_Name = watch("LastName", false);
<input id="edit-FirstName" type="text" {...register('FirstName',{ required: "Enter Your FirstName"} })} onChange={(ev)=> setValue("FullName", ev.target.value + " " + L_Name )} />
<input id="edit-LastName" type="text" {...register('LastName',{ required: "Enter Your LastName"} })} onChange={(ev)=> setValue("FullName", F_Name + " " + ev.target.value )} />
<input readOnly id="edit-FullName" type="text" {...register('FullName',{ required: "Enter Your FirstName and Last Name"} })} />
You can use a combination of useWatch and useFormContext for that type of thing.
FirstName and LastNameconst firstName = useWatch('FirstName');
const lastName = useWatch('LastName');
setValue from formContext to update desired fieldconst { setValue } = useFormContext();
undefined for FullName if any of the names is empty and concatenate them with space.const fullName = [firstName, lastName].filter(name => name).join(' ');
FullName fieldsetValue('FullName', fullName);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With