# Phone Input (/docs/phone-input)





`PhoneInput` is a phone number field with a country picker in front of it. It formats as the user types — `06 12 34 56 78` in France, `(201) 555-0123` in the US — and reports one canonical value, the [E.164](https://en.wikipedia.org/wiki/E.164) string (`"+33612345678"`), which is what a backend or an SMS provider expects.

```tsx
'use client';
import { PhoneInput } from '@42-central/ui-react/phone-input';

<PhoneInput label="Phone" defaultCountry="FR" />
```

Formatting and validation come from [libphonenumber-js](https://gitlab.com/catamphetamine/libphonenumber-js), and the flags from [country-flag-icons](https://gitlab.com/catamphetamine/country-flag-icons). The flags load in one lazy chunk on first use, so pages without a phone field never pay for them.

## Playground [#playground]

<story.Playground />

## Value [#value]

`onChange(value, details)` hands back the E.164 value, or `null` while there is no number. `details` says which country the number belongs to and whether it is complete and valid. `value` / `defaultValue` take the same E.164 string and show it in its country's national format.

<Preview code="&#x22;const [value, setValue] = useState<string | null>(\&#x22;+33612345678\&#x22;);\n\n<PhoneInput\n  label=\&#x22;Phone\&#x22;\n  value={value}\n  onChange={(next, { country, isValid }) => setValue(next)}\n/>&#x22;">
  <ControlledDemo />
</Preview>

Separators are free-form: spaces, dots, dashes and parentheses all fold into the country's own grouping.

### Typing the dial code [#typing-the-dial-code]

The dial code behaves like a token in front of the number. Typing a complete code moves it into the country trigger, and Backspace at the very start of the number takes it back out, so the whole number stays editable from the keyboard:

| Keys                   | Trigger  | Field      |
| ---------------------- | -------- | ---------- |
| `+` `3`                | 🌐       | `+3`       |
| `3`                    | 🇫🇷 +33 | *(empty)*  |
| `6` `1` `2`            | 🇫🇷 +33 | `6 12`     |
| Backspace at the start | 🌐       | `+33 6 12` |

* On an empty field, Backspace is the exact inverse of the last keystroke: 🇫🇷 with nothing typed goes back to `+3`.
* With a number after it, the code comes back whole, caret after it, and nothing is deleted. Deleting its last digit would leave `+36 12`, a Hungarian number nobody typed.
* While the caret is inside the code, it stays text. It collapses again once the code is finished (typing a `3` back, or a `2` for Belgium).
* Pasting `+44 20 7946 0958` lands as 🇬🇧 + `20 7946 0958` in one go.
* A code shared by several countries resolves to its main one, and the number refines it: `+1` shows 🇺🇸, then `204 …` (a Canadian area code) switches to 🇨🇦. A country the user picked, or passed as `defaultCountry`, is never overridden that way.

## Country [#country]

The country defaults to the region of the active locale (`fr-FR` gives France, see [`IntlProvider`](/docs/intl)). `defaultCountry` pins it, and `country` / `onCountryChange` control it. With the locale on `"auto"`, pass `defaultCountry` so the server and the first client render agree.

The list is searchable by name or dial code — typing `33` finds France — and the names are in the locale's language.

### Preferred countries [#preferred-countries]

`preferredCountries` are pinned at the top of the list, under their own heading.

<story.Preview variant="Preferred countries" />

### Allowlist [#allowlist]

`countries` limits what the list offers. A number from another country still formats, so the user sees what they typed, but `details.isValid` is `false`.

<story.Preview variant="Allowlist" />

### No country [#no-country]

`defaultCountry={null}` starts with no country: the trigger shows a globe until the user types a `+` and a dial code, which then moves into the trigger.

<story.Preview variant="No country" />

## Placeholder [#placeholder]

By default the placeholder is an example number of the selected country, written the way its people write it: `06 12 34 56 78` for France, `07400 123456` for the UK, `(201) 555-0123` for the US. It follows the country, including one resolved from a typed `+44`, and there's none while no country is selected.

A fixed string would contradict the field as soon as the country changes (`+33 …` next to a selected UK). To word it yourself, pass a function of the country; what it returns is used as-is. `placeholder=""` turns it off.

```tsx
<PhoneInput placeholder={(country) => (country ? 'Mobile number' : '+ dial code and number')} />
```

## Validation [#validation]

The field never turns red on its own: flagging a number as wrong while it's still being typed is noise. Read `details.isValid`, or validate in your schema with the same engine through `isValidPhoneNumber`, and pass `error` when the user is done — on blur, or on submit.

<Preview code="&#x22;const [valid, setValid] = useState(true);\nconst [touched, setTouched] = useState(false);\n\n<PhoneInput\n  label=\&#x22;Phone\&#x22;\n  defaultCountry=\&#x22;FR\&#x22;\n  onChange={(_, { isValid }) => setValid(isValid)}\n  onBlur={() => setTouched(true)}\n  error={touched && !valid ? \&#x22;Enter a complete phone number\&#x22; : undefined}\n/>&#x22;">
  <ValidationDemo />
</Preview>

```tsx
import { isValidPhoneNumber } from '@42-central/ui-react/phone-input';
import { z } from 'zod';

const schema = z.object({
  phone: z.string().refine((value) => isValidPhoneNumber(value), 'Enter a complete phone number'),
});
```

## Forms [#forms]

`name` submits the E.164 value with a native `<form>`. With react-hook-form, bind it through `Controller` — the value is not a DOM string, so `register` doesn't fit:

```tsx
<Controller
  name="phone"
  control={control}
  render={({ field, fieldState }) => (
    <PhoneInput
      label="Phone"
      value={field.value ?? null}
      onChange={field.onChange}
      onBlur={field.onBlur}
      ref={field.ref}
      error={fieldState.error?.message}
    />
  )}
/>
```

## Sizes [#sizes]

Five heights — `xs` through `xl` — matching the rest of the family. The flag and dial code scale with the text.

<Preview align="block" code="&#x22;<PhoneInput size=\&#x22;xs\&#x22; defaultValue=\&#x22;+33612345678\&#x22; />\n<PhoneInput size=\&#x22;sm\&#x22; defaultValue=\&#x22;+33612345678\&#x22; />\n<PhoneInput size=\&#x22;md\&#x22; defaultValue=\&#x22;+33612345678\&#x22; />\n<PhoneInput size=\&#x22;lg\&#x22; defaultValue=\&#x22;+33612345678\&#x22; />\n<PhoneInput size=\&#x22;xl\&#x22; defaultValue=\&#x22;+33612345678\&#x22; />&#x22;">
  <div className="flex w-full max-w-xs flex-col gap-3">
    <PhoneInput size="xs" defaultValue="+33612345678" />

    <PhoneInput size="sm" defaultValue="+33612345678" />

    <PhoneInput size="md" defaultValue="+33612345678" />

    <PhoneInput size="lg" defaultValue="+33612345678" />

    <PhoneInput size="xl" defaultValue="+33612345678" />
  </div>
</Preview>

## Error & disabled [#error--disabled]

<story.Preview variant="Error" />

<story.Preview variant="Disabled" />

## Custom flags [#custom-flags]

`renderFlag` draws each flag yourself — your own sprite, or emoji. Emoji flags cost nothing, but Windows shows them as two letters (`FR`), which is why the kit ships SVGs.

<Preview code="&#x22;<PhoneInput\n  defaultCountry=\&#x22;FR\&#x22;\n  renderFlag={(code) => <span aria-hidden>{toEmoji(code)}</span>}\n/>&#x22;">
  <EmojiFlagsDemo />
</Preview>

## Right to left [#right-to-left]

A phone number reads left to right in every script, so the number itself stays `dir="ltr"`; under an RTL locale it is right-aligned, and the country picker moves to the inline-start (right) edge with the rest of the shell.

## Translations [#translations]

`translations` covers the country picker's wording. Unset keys keep their English default.

```tsx
<PhoneInput
  translations={{
    triggerLabel: (country) => (country ? `Pays : ${country}` : 'Pays : aucun'),
    searchPlaceholder: 'Rechercher un pays',
    empty: 'Aucun pays trouvé',
    preferredLabel: 'Suggestions',
    allLabel: 'Tous les pays',
  }}
/>
```

## API [#api]

<TypeTable
  type="{
  value: { type: 'string | null', description: 'Controlled value, E.164 (&#x22;+33612345678&#x22;); null for empty.' },
  defaultValue: { type: 'string | null', description: 'Uncontrolled initial value, E.164.' },
  onChange: { type: '(value: string | null, details: { country: CountryCode | null; isValid: boolean }) => void', description: 'Fires with the E.164 value on every change; null while there is no number.' },
  country: { type: 'CountryCode | null', description: 'Controlled country (ISO 3166-1 alpha-2).' },
  defaultCountry: { type: 'CountryCode | null', default: &#x22;the locale's region&#x22;, description: 'Uncontrolled initial country; null for none.' },
  onCountryChange: { type: '(country: CountryCode | null) => void', description: 'Fires when the country is picked, or detected from a +… number.' },
  countries: { type: 'CountryCode[]', description: 'Only offer these countries; a number from elsewhere is not valid.' },
  preferredCountries: { type: 'CountryCode[]', description: 'Pinned at the top of the list, under their own heading.' },
  renderFlag: { type: '(country: CountryCode) => ReactNode', description: 'Draw each flag yourself. Defaults to the kit SVG flags.' },
  locale: { type: 'string', description: 'Locale for country names and the default country; defaults to the IntlProvider locale.' },
  placeholder: { type: 'string | ((country: CountryCode | null) => string | undefined)', default: &#x22;the country's example number&#x22;, description: 'Placeholder while the field is empty; a function of the country to follow it.' },
  name: { type: 'string', description: 'Field name for native form submission; submits the E.164 value.' },
  label: { type: 'ReactNode', description: 'Field label, bound to the input.' },
  description: { type: 'ReactNode', description: 'Helper text between the label and the control.' },
  error: { type: 'ReactNode', description: 'Error message below the control; flips the invalid state.' },
  required: { type: 'boolean', description: 'Marks the field required.' },
  invalid: { type: 'boolean', description: 'Red invalid state; OR’d with error.' },
  disabled: { type: 'boolean', description: 'Disables the input and the country picker.' },
  readOnly: { type: 'boolean', description: 'Blocks edits and the country picker, at full contrast.' },
  size: { type: &#x22;'xs' | 'sm' | 'md' | 'lg' | 'xl'&#x22;, default: &#x22;'md'&#x22;, description: 'Height and text scale.' },
  variant: { type: &#x22;'default' | 'unstyled'&#x22;, default: &#x22;'default'&#x22;, description: 'Shell surface.' },
  ref: { type: 'Ref<HTMLInputElement>', description: 'Lands on the input, for focus-on-error.' },
  onBlur: { type: '(event: FocusEvent<HTMLInputElement>) => void', description: 'Forwarded to the input.' },
  testId: { type: 'string', description: 'data-testid on the input.' },
  classNames: { type: '{ field?, label?, root?, country?, input?, list? }', description: 'Per-part class overrides.' },
  translations: { type: 'PhoneInputTranslations', description: 'The country picker wording.' },
  icons: { type: '{ chevron?, international? }', description: 'Replaces the trigger chevron and the no-country globe.' },
}"
/>
