how to do get react-phone-input-2 value by using react-hook-form in react

Viewed 1718

I am getting TextField value on Submit, but not ReactPhoneInput value, how to get the value using react-hook-form

import ReactPhoneInput from "react-phone-input-2"
import {TextField,Button}from "@material-ui/core"

const {register, handleSubmit,formState: { errors }} = useForm()

const getData= (data) => {
   console.log(data.username)
   console.log(data.username);
}

form

<form onSubmit={handleSubmit(getData)} >

  <TextField {...register("username")} />

   <ReactPhoneInput
      inputExtraProps={{
        name: "phone",
        required: true,
        autoFocus: true
      }}

      country={"in"}
       onlyCountries={["in"]}                     
       countryCodeEditable={false}
        specialLabel={"Player Mobile Number"}
       rules={{ required: true }}
     />
<Button type='submit>Submit</Button> 
</form>
1 Answers

<ReactPhoneInput /> is an external controlled component and therefore you should use RHF's <Controller /> component here. Check this section in the docs for more infos.

<Controller
  control={control}
  name="phone"
  rules={{ required: true }}
  render={({ field: { ref, ...field } }) => (
    <ReactPhoneInput
      {...field}
      inputExtraProps={{
        ref,
        required: true,
        autoFocus: true
      }}
      country={"in"}
      onlyCountries={["in"]}
      countryCodeEditable={false}
      specialLabel={"Player Mobile Number"}
    />
  )}
/>

Edit React Hook Form - react-phone-input-2

Related