Search code examples
javascriptreactjsreact-nativereact-props

React Cannot read property 'name' of undefined on [event.target.name]


I have a 3rd-party component using Phone Input here https://github.com/bl00mber/react-phone-input-2#react-phone-input-2 I need to get the value input by the user and set the form state using the method below that handles onChange:

const handlePhoneChange = (event) => {
  setFormState({
    ...formState,
    [event.target.name]: event.target.value,
  });
};

This is my configuration for the 3rd-party component below:

<PhoneInput
      country={"us"}
      error={hasError("phone")}
      helperText={hasError("phone") ? formState.errors.phone[0] : null}
      name="phone"
      value={formState.values.phone || ""}
      onChange={handlePhoneChange}
    />

However, I get the error TypeError: Cannot read property 'name' of undefined when I try to type a number in the phoneInput component. Kindly help me resolve this.


Solution

  • If you read the documentation for the onchange event, there are 4 arguments that are accessible: onChange(value, country, e, formattedValue).

    The way you're accessing event is incorrect, because you're accessing the first positional arugment, which is the value of the input. You get an error trying to access event.target since it is not an Event object.

    The Event object is available as the third positional argument, so if you use it as such, it should work:

    const handlePhoneChange = (value, country, event) => {
      setFormState({
        ...formState,
        [event.target.name]: value,
      });
    };