Phone Input
A phone number field with a searchable country picker.
import { Div, signal, Span } from "@implementjs/core";
import { PhoneInput, type CountryCode } from "@/lib/components/ui/phone-input";
export default function PhoneInputDemo() {
const value = signal("");
const country = signal<CountryCode | null>("US");
return Div(
{ class: "flex w-full max-w-sm flex-col gap-2" },
PhoneInput({ value, country, placeholder: "Enter a phone number" }),
Span(
{ class: "text-sm text-muted-foreground" },
value.bind((v) => (v === "" ? "Enter a phone number." : `E.164: ${v}`)),
),
);
}Installation
npx jsrepo add @implementjs/ui/phone-input
It installs @implementjs/lucide and country-flag-icons at the same time, plus the popover and command components it is built from.
Copy the file below to src/lib/components/ui/phone-input.ts, along with popover.ts and command.ts (and what they need). It imports cn from @implementjs/cn. Then, on top of @implementjs/core and @implementjs/primitives:
npm install @implementjs/lucide country-flag-icons
import {
Html,
ImplementEffect,
isReadable,
signal,
Span,
type Child,
type ComponentProps,
type Readable,
} from "@implementjs/core";
import { CheckIcon, ChevronsUpDownIcon } from "@implementjs/lucide";
import {
createComponent,
getPhoneCountries,
PhoneInput as PhoneInputPrimitive,
PhoneInputContext,
PhoneInputField,
type CountryCode,
type PhoneCountry,
type PhoneInputFieldProps,
} from "@implementjs/primitives";
import { cn } from "@implementjs/cn";
import { Command, CommandEmpty, CommandInput, CommandItem, CommandList } from "./command";
import { Popover, PopoverContent, PopoverPortal, PopoverTrigger } from "./popover";
export { getPhoneCountries } from "@implementjs/primitives";
export type { CountryCode, PhoneCountry } from "@implementjs/primitives";
export type PhoneInputProps = ComponentProps<typeof PhoneInputPrimitive> & {
placeholder?: string;
/** Props for the number field — an `aria-label`, `aria-invalid`, or an event handler. */
inputProps?: PhoneInputFieldProps;
/** The countries to offer, in the order to show them. Defaults to every country, by name. */
countries?: PhoneCountry[];
};
let flagIcons: Promise<Record<string, string>> | null = null;
/** The flag SVGs are large, so they load the first time one is drawn. */
function loadFlags() {
flagIcons ??= import("country-flag-icons/string/3x2").then((module) => ({ ...module }));
return flagIcons;
}
function Flag(country: Readable<CountryCode | null> | CountryCode | null) {
const svg = signal("");
const code = isReadable(country) ? country : signal(country);
return Span(
{
"data-slot": "phone-input-flag",
class:
"flex h-4 w-6 shrink-0 overflow-clip rounded-sm bg-foreground/20 [&>svg]:h-full! [&>svg]:w-full!",
},
ImplementEffect([code], (current) => {
if (current === null) {
svg.set("");
return;
}
void loadFlags().then((icons) => {
if (code.get() === current) svg.set(icons[current] ?? "");
});
}),
// the SVGs come from the country-flag-icons package, never from user input
// oxlint-disable-next-line implementjs/no-html
Html(svg),
);
}
function CountrySelect(countries: PhoneCountry[]) {
return PhoneInputContext.Use((state) => {
const open = signal(false);
return Popover(
{ open },
PopoverTrigger(
{
variant: "outline",
"aria-label": "Select country",
disabled: state.disabled,
class: "shrink-0 gap-1 rounded-r-none px-3",
},
Flag(state.country),
ChevronsUpDownIcon({ class: "-mr-1 size-4 opacity-50", "aria-hidden": true }),
),
PopoverPortal(
PopoverContent(
{ class: "w-[300px] p-0" },
Command(
{ label: "Country" },
CommandInput({ placeholder: "Search..." }),
CommandList(
CommandEmpty("No country found."),
...countries.map((country) =>
CommandItem(
{
value: country.name,
keywords: [country.code, country.dialCode],
onSelect: () => {
state.setCountry(country.code);
open.set(false);
// after the popover hands focus back to its trigger
setTimeout(() => state.focus(), 0);
},
},
Flag(country.code),
Span({ class: "flex-1 truncate" }, country.name),
Span({ class: "text-muted-foreground" }, `+${country.dialCode}`),
CheckIcon({
class: state.country.bind((current) =>
cn("size-4", current === country.code ? "opacity-100" : "opacity-0"),
),
"aria-hidden": true,
}),
),
),
),
),
),
),
);
});
}
export const PhoneInput = createComponent(function PhoneInput(
{ class: className, placeholder, inputProps, countries, ...props }: PhoneInputProps,
...children: Child[]
) {
const list = countries ?? getPhoneCountries();
return PhoneInputPrimitive(
{ ...props, "data-slot": "phone-input", class: cn("flex items-center", className) },
CountrySelect(list),
PhoneInputField({
placeholder,
...inputProps,
"data-slot": "phone-input-field",
class: cn(
"relative -ml-px flex h-9 w-full min-w-0 rounded-l-none rounded-r-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none md:text-sm",
"placeholder:text-muted-foreground",
"selection:bg-primary selection:text-primary-foreground",
"focus-visible:z-10 focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
"aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",
"disabled:cursor-not-allowed disabled:opacity-50",
"dark:bg-input/30",
inputProps?.class,
),
}),
...children,
);
});Usage
import { signal } from "@implementjs/core";
import { PhoneInput, type CountryCode } from "@/lib/components/ui/phone-input";
const country = signal<CountryCode | null>("US");
const value = signal("");
PhoneInput({ country, value, placeholder: "Enter a phone number" });
value is the number in E.164 form. Typing a number that starts with + picks its country for you.
Countries
Offer fewer countries, or in your own order, by passing countries:
import { getPhoneCountries } from "@/lib/components/ui/phone-input";
const all = getPhoneCountries();
const first = ["US", "CA", "GB"];
const countries = [
...all.filter((c) => first.includes(c.code)),
...all.filter((c) => !first.includes(c.code)),
];
PhoneInput({ countries });
Invalid
Pass aria-invalid to the number field and it takes the destructive border:
PhoneInput({ inputProps: { "aria-invalid": true } });
API Reference
Every prop the styling does not consume is forwarded to the Phone Input primitive, so the tables below are the whole surface.
PhoneInput
A phone input, fully assembled: a searchable country picker beside the number field. Every root prop below is forwarded. Renders a Div; extra props are forwarded onto it.
| Prop | Type | Default | Description |
|---|---|---|---|
placeholder | string | — | Placeholder for the number field. |
inputProps | ElementProps<"input"> | — | Props for the number field — an aria-label, aria-invalid, or an event handler. |
countries | PhoneCountry[] | — | The countries to offer, in the order to show them. Defaults to getPhoneCountries(), every country sorted by name. |
country | Signal<CountryCode | null> | CountryCode | null | null | The selected country, as an ISO 3166-1 alpha-2 code. Pass a signal to control it from outside. Typing a number that starts with + sets it. |
onCountryChange | (country: CountryCode | null) => void | — | Runs whenever the country changes. |
value | Signal<string> | string | "" | The number in E.164 form, like "+15551234567". Pass a signal to control it from outside. |
onValueChange | (value: string) => void | — | Runs whenever the number changes. |
valid | Signal<boolean> | — | Receives whether the number is complete and valid for its country. An empty field counts as valid. |
disabled | Readable<boolean> | boolean | false | Disables the field. |
readOnly | boolean | false | Makes the field read-only. |
name | string | — | Submits the E.164 number with a form under this name. |
| Data attribute | Value |
|---|---|
[data-phone-input-root] | Present |
[data-disabled] | Present when disabled |
[data-valid] | "false" when the number is not valid |