UNPKG

coject

Version:
66 lines 3.32 kB
import React, { useEffect, useState } from "react"; // React Hook Form import { useFormContext } from "react-hook-form"; // Material UI import { TextField, Autocomplete, InputAdornment } from "@mui/material"; // Countries const countries = [ { code: "+966", label: "Saudi Arabia" }, { code: "+20", label: "Egypt" }, { code: "+1", label: "USA" }, { code: "+44", label: "UK" }, { code: "+971", label: "UAE" }, { code: "+965", label: "Kuwait" }, { code: "+974", label: "Qatar" }, { code: "+973", label: "Bahrain" }, { code: "+968", label: "Oman" }, { code: "+962", label: "Jordan" }, { code: "+961", label: "Lebanon" }, { code: "+964", label: "Iraq" }, { code: "+90", label: "Turkey" } ]; export const InternationalPhone = ({ name, label, value, required, fullWidth, disabled, onChange }) => { const { setValue } = useFormContext(); const [phone, setPhone] = useState(""); const [touched, setTouched] = useState(false); const [country, setCountry] = useState(countries[0]); // Handle Country Code useEffect(() => { if (!value) return; const matched = countries.find((c) => value.startsWith(c.code)); if (matched) { setCountry(matched); setPhone(value.replace(matched.code, "")); } }, [value]); // Handle Value useEffect(() => { const fullNumber = `${country.code}${phone}`; setValue(name, fullNumber, { shouldValidate: true }); if (onChange) onChange(fullNumber); }, [country, phone, name, setValue, onChange]); return (React.createElement(React.Fragment, null, React.createElement(TextField, { disabled: disabled, fullWidth: fullWidth, label: label || "Phone Number", value: phone, required: !!required, dir: "ltr", helperText: touched && !!required && !phone ? (typeof required === "string" ? required : "This Field Is Required") : "", onBlur: () => setTouched(true), onChange: (e) => setPhone(e.target.value.replace(/\D/g, "")), inputProps: { inputMode: "numeric", dir: "ltr" }, InputProps: { startAdornment: (React.createElement(InputAdornment, { position: "start" }, React.createElement(Autocomplete, { disableClearable: true, options: countries, value: country, disabled: disabled, onChange: (_, v) => v && setCountry(v), getOptionLabel: (o) => o.code, sx: { width: 90, "& .MuiInputBase-root": { paddingRight: "18px", paddingLeft: "4px" }, "& .MuiAutocomplete-popupIndicator": { marginRight: "-2px" }, "& .MuiAutocomplete-input": { padding: "4px 0 !important", textAlign: "center" } }, renderInput: (params) => (React.createElement(TextField, { ...params, variant: "standard", InputProps: { ...params.InputProps, disableUnderline: true } })) }))), } }))); }; //# sourceMappingURL=index.js.map