fix(SW-1095): set country code based on url lang when phone input empty

This commit is contained in:
Chuma McPhoy
2024-11-29 09:20:50 +01:00
parent dde953c270
commit 4da0918469
2 changed files with 30 additions and 7 deletions

View File

@@ -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({
</div>
)
}
function getDefaultCountryFromLang(lang: Lang): LowerCaseCountryCode {
const countryMap: Record<Lang, LowerCaseCountryCode> = {
sv: "se",
da: "dk",
fi: "fi",
no: "no",
de: "de",
en: "gb",
}
return countryMap[lang] || "se"
}

View File

@@ -1,12 +0,0 @@
import type { RegisterOptions } from "react-hook-form"
export type PhoneProps = {
ariaLabel?: string
className?: string
disabled?: boolean
label: string
name?: string
placeholder?: string
readOnly?: boolean
registerOptions?: RegisterOptions
}