diff --git a/components/TempDesignSystem/Form/Phone/index.tsx b/components/TempDesignSystem/Form/Phone/index.tsx index 9c413fc0a..8c5c91fa3 100644 --- a/components/TempDesignSystem/Form/Phone/index.tsx +++ b/components/TempDesignSystem/Form/Phone/index.tsx @@ -12,17 +12,20 @@ import { } from "react-international-phone" import { useIntl } from "react-intl" +import { Lang } from "@/constants/languages" + import { ChevronDownIcon } from "@/components/Icons" import ErrorMessage from "@/components/TempDesignSystem/Form/ErrorMessage" import AriaInputWithLabel from "@/components/TempDesignSystem/Form/Input/AriaInputWithLabel" import Label from "@/components/TempDesignSystem/Form/Label" import Body from "@/components/TempDesignSystem/Text/Body" +import useLang from "@/hooks/useLang" import styles from "./phone.module.css" import type { ChangeEvent } from "react" -import type { PhoneProps } from "./phone" +import { LowerCaseCountryCode, PhoneProps } from "@/types/components/form/phone" export default function Phone({ ariaLabel = "Phone number input", @@ -37,6 +40,7 @@ export default function Phone({ }, }: PhoneProps) { const intl = useIntl() + const lang = useLang() const { control, setValue, trigger } = useFormContext() const phone = useWatch({ name }) @@ -47,13 +51,17 @@ export default function Phone({ rules: registerOptions, }) + const defaultPhoneNumber = formState.defaultValues?.phoneNumber + + // If defaultPhoneNumber exists and is valid, parse it to get the country code, + // otherwise set the default country from the lang. + const defaultCountry = isValidPhoneNumber(defaultPhoneNumber) + ? parsePhoneNumber(defaultPhoneNumber).country?.toLowerCase() + : getDefaultCountryFromLang(lang) + const { country, handlePhoneValueChange, inputValue, setCountry } = usePhoneInput({ - defaultCountry: isValidPhoneNumber(formState.defaultValues?.phoneNumber) - ? parsePhoneNumber( - formState.defaultValues?.phoneNumber - ).country?.toLowerCase() - : "se", + defaultCountry, disableDialCodeAndPrefix: true, forceDialCode: true, value: phone, @@ -142,3 +150,15 @@ export default function Phone({ ) } + +function getDefaultCountryFromLang(lang: Lang): LowerCaseCountryCode { + const countryMap: Record = { + sv: "se", + da: "dk", + fi: "fi", + no: "no", + de: "de", + en: "gb", + } + return countryMap[lang] || "se" +} diff --git a/components/TempDesignSystem/Form/Phone/phone.ts b/types/components/form/phone.ts similarity index 61% rename from components/TempDesignSystem/Form/Phone/phone.ts rename to types/components/form/phone.ts index f7dbd0e15..537c17cc1 100644 --- a/components/TempDesignSystem/Form/Phone/phone.ts +++ b/types/components/form/phone.ts @@ -1,6 +1,9 @@ +import type { CountryCode } from "libphonenumber-js/min" import type { RegisterOptions } from "react-hook-form" -export type PhoneProps = { +export type LowerCaseCountryCode = Lowercase + +export interface PhoneProps { ariaLabel?: string className?: string disabled?: boolean