Search code examples
reactjstypescriptformsreact-hook-formreact-select

React Hook Form controlled component. Two inputs as one single value


I'm trying to create a combo component/input field that will consists of a dropdown list and simple text field. I assume I need to use the useController option from react hook form but this is as far I can go. I know for sure that I can pass two names to that component and get two values separately in order to merge them as one during submit but... I want to get a single value out of those two fields if possible.

For example the select field has the options of countries phone prefixes and the input field will be free. So if I get the value +44 for the select and the value 1234567890 I want to merge them as a single value. Meaning +441234567890.

I used the register and control from react-hook-form but I have no clue on how to merge those values as one.

Any help or examples unifying two input fields as one would be greatly appreciated.


Solution

  • If you are using react-hook-form there is a concept watch. you can watch the changes happening to a field or fields.

    const { register, handleSubmit, watch } = useForm();
    
      const watchFields = watch(["code", "phone"]);
    

    Here is a working sample