Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a input field based on other inputs in react-hook-form

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"} })}  />
like image 703
Joy Avatar asked Dec 13 '25 20:12

Joy


1 Answers

You can use a combination of useWatch and useFormContext for that type of thing.

  1. Watch for changes of FirstName and LastName
const firstName = useWatch('FirstName');
const lastName = useWatch('LastName');
  1. Get setValue from formContext to update desired field
const { setValue } = useFormContext();
  1. Ensure you don't end up with undefined for FullName if any of the names is empty and concatenate them with space.
const fullName = [firstName, lastName].filter(name => name).join(' ');
  1. Update your FullName field
setValue('FullName', fullName);
like image 64
Kuker Avatar answered Dec 16 '25 13:12

Kuker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!