UNPKG

@pagamio/frontend-commons-lib

Version:

Pagamio library for Frontend reusable components like the form engine and table container

59 lines (58 loc) 3.1 kB
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime"; import { ParseError, isPossiblePhoneNumber, parsePhoneNumberWithError } from 'libphonenumber-js'; import ReachPhoneNumberInput from 'react-phone-number-input'; import 'react-phone-number-input/style.css'; import React, { useState } from 'react'; const PhoneInput = React.forwardRef(({ field, error, onChange, onBlur, value, onCountryChange, ...props }, ref) => { const [isTouched, setIsTouched] = useState(false); const [localError, setLocalError] = useState(null); const defaultCountry = field.defaultCountry ?? 'ZA'; const isValid = !value || isPossiblePhoneNumber(value); const handleChange = (newValue) => { onChange?.(newValue); setLocalError(null); if (newValue) { try { const phoneNumber = parsePhoneNumberWithError(newValue, { defaultCountry }); if (phoneNumber && onCountryChange) { onCountryChange(phoneNumber.country); } } catch (error) { if (error instanceof ParseError) { switch (error.message) { case 'NOT_A_NUMBER': setLocalError('Please enter a valid phone number.'); break; case 'INVALID_COUNTRY': setLocalError('Invalid or unsupported country.'); break; case 'TOO_SHORT': setLocalError('Phone number is too short.'); break; case 'TOO_LONG': setLocalError('Phone number is too long.'); break; default: setLocalError('Invalid phone number.'); } } else { console.error('Unexpected error:', error); } } } }; const handleBlur = () => { setIsTouched(true); onBlur?.(); }; return (_jsxs(_Fragment, { children: [_jsx("label", { htmlFor: field.name, className: "block text-sm font-medium text-gray-700", children: field.label }), _jsx(ReachPhoneNumberInput, { international: true, defaultCountry: defaultCountry, value: value || '', onChange: handleChange, id: field.name, onBlur: handleBlur, placeholder: field.placeholder, numberInputProps: { className: `mt-1 block w-full p-2 border rounded-md shadow-sm ${error || localError ? 'border-red-500' : 'border-gray-300'} ${field.disabled ? 'text-gray-400 bg-gray-50' : ''}`, disabled: field.disabled, ref: ref, }, ...props }), (error || localError || (!isValid && isTouched)) && (_jsx("p", { className: "mt-2 text-sm text-red-500", children: error?.message ?? localError ?? 'Please enter a valid phone number' }))] })); }); export default PhoneInput;