tkym
tkym

Reputation: 43

PhoneInputWithCountry component can not set value by event

I'm using PhoneInputWithCountry component from react-phone-number-input on Next.js 14. I want to set value on the PhoneInputWithCountry component when user clicks checkbox. So I set the value as 'defaultValue' and 'Value' property, but it doesn't work. Could you help me to set the value?

export default function Home() {
  const { control } = useForm();
  const [tel, setTel] = useState("");
  const specialTel = "+1 604 111 1111";

  // fill tel value * it doesn't set
  const fillValue = (isChecked: boolean) => {
    if (isChecked == true) {
      setTel(specialTel);
    } else {
      console.log("false");
    }
  };

  return (
    <>
      <div className="w-[150px]" style={{ width: "150px" }}>
        <label htmlFor="specialTel">Set Special Tel</label>
        <input
          id="specialTel"
          type="checkbox"
          onChange={(event) => fillValue(event.target.checked)}
        />
        <PhoneInputWithCountry
          name="tel"
          value={tel}
          defaultValue={tel}
          control={control}
          countries={["CA"]}
          addInternationalOption={false}
          defaultCountry="CA"
          min={10}
          international={true}
          limitMaxLength={true}
          onChange={(val: string) => {
            console.log(val);
            setTel(val);
          }}
        />
      </div>
    </>
  );
}

CodeSandBox

Upvotes: 0

Views: 271

Answers (1)

tkym
tkym

Reputation: 43

I found the solution. Based on the following, I can not use PhoneInputWithCountry when I want to set value after rendered. Because it doesn't accept 'value' property. https://gitlab.com/catamphetamine/react-phone-number-input/-/issues/72

So, I have to use other components(e.g. PhoneInputWithCountrySelect). About my code, just need to import 'PhoneInputWithCountrySelect' and change PhoneInputWithCountry to PhoneInputWithCountrySelect then it works.

return (
    ....
      <PhoneInputWithCountrySelect
        name="tel"
        value={tel}
        defaultValue={tel}
        control={control}
        countries={["CA"]}
        addInternationalOption={false}
        defaultCountry="CA"
        min={10}
        international={true}
        limitMaxLength={true}
        onChange={(val: string) => {
          console.log(val);
          setTel(val);
        }}
      />
  ...
);

Upvotes: 0

Related Questions