简体   繁体   中英

React phone input number value formt issue

I have the following: ( http://catamphetamine.github.io/react-phone-number-input/ )

type PhoneNumberInputProps = {
  dataBdd: string
  disabled: boolean | undefined,
  label?: string,
  id: string
  onChange: any
  value: string
  error?: any
  maxLength?: number
}

const PhoneNumberInput: React.FC<PhoneNumberInputProps> = ({
  dataBdd,
  disabled,
  id,
  onChange,
  label,
  value,
  error
}) => {

  const phoneInputStyle = classNames({
    'error': error,
    'hide': disabled
  });

  const [updatedValue, setUpdatedValue] = useState(value)

  useEffect(() => {
    setUpdatedValue(value)
  }, [value])

  const DEFAULT_COUNTRY_VALUE = 'GB'

  const handleOnChange = (val: string) => {
    setUpdatedValue(val)
    onChange(val)
  }

  return (
    <>
      <Label htmlFor={id}>{label}</Label>
      <PhoneInput
        data-bdd={dataBdd}
        disabled={disabled}
        id={id}
        defaultCountry={DEFAULT_COUNTRY_VALUE}
        value={updatedValue}
        onChange={handleOnChange}
        className={phoneInputStyle}
        maxLength={15}
      />
    </>
  )
}

export default PhoneNumberInput;

if I change the value of a phone number the ui gets updated correctly and the value property gets the + in front of the number which is what I send to the BE.

But, if there is a default value coming from the BE and I don't change that number so it doesn't get formatted the value gets sent without the +.

Is it possible to format the value regardless of the onChange being triggered?

Format the Value before setting the state in useEffect.

 import PhoneInput, { formatPhoneNumber, formatPhoneNumberIntl } from 'react-phone-number-input' <PhoneInput placeholder="Enter phone number" value={value} onChange={setValue}/> National: {value && formatPhoneNumber(value)} International: {value && formatPhoneNumberIntl(value)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM