# Address Form

> A shipping or billing address form that changes with the country. Handles address search, postal codes, saved addresses and error summaries.

Canonical: https://hextaui.com/blocks/address-form
Last updated: 2026-10-29

## Overview

Address Form asks for an address the way the shopper’s country writes it. A US address gets City, State and ZIP code on one row, the UK gets Town or city and Postcode with no state, Germany puts the postal code before the city, and Japan starts with the postal code and prefecture. Sixteen countries have their own format with labels, required fields, region lists and postal rules, and every other country gets a plain fallback.

Fewer fields come first. Full name is one field, Company and Apartment sit behind small links, and the phone is optional with the reason under it. Every input has the right autocomplete token with a shipping or billing prefix, the right keyboard on phones and a name, so browser autofill fills the whole form at once, including the hidden apartment field.

Errors show when you leave a field, then update as you type until it’s fixed, and they say what’s wrong: “Enter a 5-digit ZIP code”, “Enter a postcode like SW1A 1AA”. validate() lists every problem in a summary at the top with links to the fields and moves focus there. Switching country keeps what still fits, clears regions that don’t, and re-checks only fields you’ve already visited, while the form’s height animates to the new layout.

Pass onSearchAddress and onResolveAddress to suggest addresses as the shopper types, with Enter address manually always at the end of the list. onLookupPostalCode fills city and region from a postal code without overwriting anything typed. SavedAddresses lists a signed-in shopper’s addresses with a Default badge, and AddressSummary is the one-line Ship to row for a finished checkout step.

## Installation

### Step 1: Get HextaUI Pro

One payment unlocks every block, including future ones. [See pricing](https://hextaui.com/pricing).

### Step 2: Add the Pro registry to components.json

```json title="components.json"
{
  "registries": {
    "@hextaui-pro": {
      "url": "https://hextaui.com/r/pro/{name}.json",
      "headers": {
        "Authorization": "Bearer ${HEXTAUI_PRO_TOKEN}"
      }
    }
  }
}
```

### Step 3: Add your token

Create a token on your [account page](https://hextaui.com/account) and put it in `.env.local` as `HEXTAUI_PRO_TOKEN`.

### Step 4: Add the block

```bash
npx shadcn@latest add @hextaui-pro/address-form
```

## Usage

### Address search with Google Places

onSearchAddress returns suggestions for what’s typed and onResolveAddress turns the picked one into an Address. The same two calls map onto Mapbox Search Box’s /suggest and /retrieve. Both get an AbortSignal, so stale requests are cancelled.

```tsx
"use client"

import type { Address } from "@/components/blocks/address-form/address"
import { AddressForm } from "@/components/blocks/address-form/address-form"
import type { AddressSuggestion } from "@/components/blocks/address-form/address-search"

const key = process.env.NEXT_PUBLIC_GOOGLE_MAPS_KEY ?? ""

type Prediction = {
  placePrediction: {
    placeId: string
    structuredFormat: {
      mainText: { text: string }
      secondaryText?: { text: string }
    }
  }
}

type Component = { longText: string; shortText: string; types: string[] }

async function searchAddresses(
  query: string,
  { country, signal }: { country: string; signal: AbortSignal }
): Promise<AddressSuggestion[]> {
  const response = await fetch(
    "https://places.googleapis.com/v1/places:autocomplete",
    {
      method: "POST",
      signal,
      headers: { "Content-Type": "application/json", "X-Goog-Api-Key": key },
      body: JSON.stringify({
        input: query,
        includedRegionCodes: [country.toLowerCase()],
        includedPrimaryTypes: ["street_address", "premise", "subpremise"],
      }),
    }
  )
  if (!response.ok) throw new Error("Address search failed")
  const { suggestions = [] } = (await response.json()) as {
    suggestions?: Prediction[]
  }
  return suggestions.map(({ placePrediction }) => ({
    id: placePrediction.placeId,
    title: placePrediction.structuredFormat.mainText.text,
    description: placePrediction.structuredFormat.secondaryText?.text,
  }))
}

async function resolveAddress(
  id: string,
  { signal }: { signal: AbortSignal }
): Promise<Partial<Address>> {
  const response = await fetch(`https://places.googleapis.com/v1/places/${id}`, {
    signal,
    headers: {
      "X-Goog-Api-Key": key,
      "X-Goog-FieldMask": "addressComponents",
    },
  })
  if (!response.ok) throw new Error("We couldn’t load that address. Enter the rest below.")
  const { addressComponents = [] } = (await response.json()) as {
    addressComponents?: Component[]
  }
  const find = (type: string, short = false) => {
    const part = addressComponents.find((item) => item.types.includes(type))
    return short ? part?.shortText : part?.longText
  }
  return {
    line1: [find("street_number"), find("route")].filter(Boolean).join(" "),
    line2: find("subpremise"),
    city: find("locality") ?? find("postal_town") ?? find("sublocality"),
    region: find("administrative_area_level_1", true),
    postalCode: find("postal_code"),
    country: find("country", true),
  }
}

export function ShippingAddress() {
  return (
    <AddressForm
      defaultCountry="US"
      onSearchAddress={searchAddresses}
      onResolveAddress={resolveAddress}
    />
  )
}
```

### Save to a Shopify customer account

validate() returns the errors and focuses the summary, so saving only runs on a complete address. The Address maps to customerAddressCreate field by field, and a userError from Shopify shows under the form.

```tsx
"use client"

import * as React from "react"

import { Button } from "@/components/ui/button"

import type { Address } from "@/components/blocks/address-form/address"
import { AddressForm, type AddressFormActions } from "@/components/blocks/address-form/address-form"

const mutation = `
  mutation customerAddressCreate($address: CustomerAddressInput!) {
    customerAddressCreate(address: $address, defaultAddress: false) {
      customerAddress { id }
      userErrors { field message }
    }
  }
`

function toShopify(address: Address) {
  const [firstName, ...rest] = address.name.trim().split(/\s+/)
  return {
    firstName,
    lastName: rest.join(" "),
    company: address.company,
    address1: address.line1,
    address2: address.line2,
    city: address.city,
    zoneCode: address.region,
    zip: address.postalCode,
    territoryCode: address.country,
    phoneNumber: address.phone,
  }
}

async function saveAddress(address: Address) {
  const response = await fetch("/api/customer-account/graphql", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      query: mutation,
      variables: { address: toShopify(address) },
    }),
  })
  const { data } = (await response.json()) as {
    data: {
      customerAddressCreate: { userErrors: { message: string }[] }
    }
  }
  const [error] = data.customerAddressCreate.userErrors
  if (error) throw new Error(error.message)
}

export function AddAddress({ onSaved }: { onSaved: () => void }) {
  const formRef = React.useRef<AddressFormActions>(null)
  const [address, setAddress] = React.useState<Address>()
  const [error, setError] = React.useState<string | null>(null)

  const save = async () => {
    if (!address || formRef.current?.validate().length) return
    setError(null)
    try {
      await saveAddress(address)
      onSaved()
    } catch (reason) {
      setError(reason instanceof Error ? reason.message : String(reason))
      throw reason
    }
  }

  return (
    <div className="flex flex-col gap-6">
      <AddressForm
        actionsRef={formRef}
        onValueChange={setAddress}
        phone="required"
      />
      {error ? (
        <p role="alert" className="text-sm text-destructive">
          {error}
        </p>
      ) : null}
      <Button feedback successLabel="Saved" onClick={save}>
        Save address
      </Button>
    </div>
  )
}
```

### A billing section

Billing defaults to the shipping address and shows it as one line. Unticking the box opens a second form with section="billing", so browsers autofill billing tokens there instead of shipping ones.

```tsx
"use client"

import * as React from "react"

import { Checkbox } from "@/components/ui/checkbox"
import { Field, FieldLabel } from "@/components/ui/field"

import type { Address } from "@/components/blocks/address-form/address"
import { AddressForm } from "@/components/blocks/address-form/address-form"
import { AddressSummary } from "@/components/blocks/address-form/address-summary"
import { Reveal } from "@/components/blocks/address-form/reveal"

export function BillingAddress({
  shipping,
  onBillingChange,
}: {
  shipping: Address
  onBillingChange: (billing: Address | null) => void
}) {
  const [same, setSame] = React.useState(true)

  return (
    <div className="flex flex-col">
      <Field orientation="horizontal">
        <Checkbox
          id="billing-same"
          checked={same}
          onCheckedChange={(checked) => {
            setSame(checked === true)
            if (checked === true) onBillingChange(null)
          }}
        />
        <FieldLabel htmlFor="billing-same">
          Billing address is the same as shipping
        </FieldLabel>
      </Field>
      {same ? (
        <AddressSummary
          className="mt-3"
          label="Bill to"
          address={shipping}
        />
      ) : null}
      <Reveal open={!same} inert>
        <AddressForm
          section="billing"
          phone="hidden"
          company={false}
          defaultCountry={shipping.country}
          onValueChange={onBillingChange}
        />
      </Reveal>
    </div>
  )
}
```

## Anatomy

The parts you compose, from the outside in.

| Part | Description |
| --- | --- |
| `AddressForm` | The country-aware fields, the error summary and the address search. |
| `SavedAddresses` | Saved addresses as radio cards, with Use a new address revealing the form. |
| `AddressSummary` | The completed-step row: Ship to, the address on one line and Change. |
| `getCountryFormat, validateAddress, formatAddressLines` | Country rules, validation and formatting that also work on the server. |

## API reference

### AddressForm

Also takes div props.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `Address` | – | The address when controlled. |
| `defaultValue` | `Partial<Address>` | – | The starting address when uncontrolled. |
| `onValueChange` | `(address: Address) => void` | – | Called on every change. Regions are codes for countries with a list, such as CA or JP-13. |
| `section` | `"shipping" \| "billing"` | `"shipping"` | Prefix for autocomplete tokens and field names. |
| `countries` | `string[]` | – | ISO codes shoppers can pick, sorted by name. Defaults to every country. |
| `defaultCountry` | `string` | `"US"` | The starting country when the value has none. |
| `phone` | `"optional" \| "required" \| "hidden"` | `"optional"` | Whether to ask for a phone number. |
| `company` | `boolean` | `true` | Offer Add company. |
| `onSearchAddress` | `(query, { country, signal }) => Promise<AddressSuggestion[]>` | – | Suggest addresses as the shopper types three or more characters. Throwing shows that search isn’t available. |
| `onResolveAddress` | `(id, { signal }) => Promise<Partial<Address>>` | – | Turn a picked suggestion into an address. A different country switches the form. Throw to show your message under the field. |
| `onLookupPostalCode` | `(postalCode, { country, signal }) => Promise<{ city?; region? } \| null>` | – | Fill empty city and region fields from a valid postal code. |
| `actionsRef` | `Ref<AddressFormActions>` | – | validate() returns { field, message }[] and shows the summary, focus(field), setCountry(code) and reset(address). |
| `labels` | `Partial<AddressFormLabels>` | – | Every word the form shows or announces. |
| `locale` | `Intl.LocalesArgument` | `"en-US"` | Locale for country names and sorting. |
| `disabled` | `boolean` | – | Disable every field. |

### SavedAddresses

Also takes div props.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `addresses` | `(Address & { id: string; isDefault?: boolean })[]` | – | Saved addresses in display order. |
| `value` | `string` | – | The chosen id, or "new". |
| `defaultValue` | `string` | – | Starts on the default address, the first one, or "new" when there are none. |
| `onValueChange` | `(value: string, address?: SavedAddress) => void` | – | Called when the choice changes. |
| `onEdit` | `(address: SavedAddress) => void` | – | Shows an Edit button on each card. |
| `allowNew` | `boolean` | `true` | Show Use a new address. |
| `children` | `ReactNode` | – | Shown under the list while Use a new address is chosen, usually an AddressForm. |
| `labels` | `Partial<SavedAddressesLabels>` | – | Group name, Default, new address and edit wording. |

### AddressSummary

Also takes div props.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `address` | `Address` | – | The address to show on one line. |
| `label` | `string` | `"Ship to"` | The row label. |
| `onChange` | `() => void` | – | Shows Change. |
| `country` | `boolean` | `false` | Add the country name. |

### AddressSuggestion

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `id` | `string` | – | Passed to onResolveAddress. |
| `title` | `string` | – | The street line, shown first and put in the field when picked. |
| `description` | `string` | – | The rest, such as San Francisco, CA 94105. |
| `address` | `Partial<Address>` | – | Used directly when there’s no onResolveAddress. |

## Keyboard

| Key | Action |
| --- | --- |
| `ArrowDown` `ArrowUp` | Moves through country or address suggestions. |
| `Enter` | Picks the highlighted country or address. |
| `Escape` | Closes the suggestions and keeps what you typed. |
| `Tab` | Moves through the fields in the country’s order. Hidden company and apartment fields are skipped until opened. |

## Accessibility

- Every field has a visible label, and optional fields say Optional. Errors are linked with aria-invalid and aria-describedby and use text next to the red outline, never color alone.
- validate() moves focus to a summary titled There is a problem. Each item is a link worded like the inline error that focuses its field.
- Address search is an ARIA combobox. A polite live region says how many addresses were found, when the address was filled in, when a postal code filled the city and when the fields changed for a new country.
- Reveals and the country reflow animate height and fade, and turn off under reduced motion. Text fields use 16px text and a 48px height on touch screens.

## Built with

The free HextaUI components Address Form is made from. Each one installs on its own.

- [Badge](https://hextaui.com/docs/badge) - Status labels with colored dots, removable tags that slide closed and counts that roll to their new value.
- [Button](https://hextaui.com/docs/button) - Buttons in every variant and size, with a built-in loading, success and error flow that skips the spinner for fast requests.
- [Combobox](https://hextaui.com/docs/combobox) - A filterable select with chips, groups and async results, in a popup that resizes as you type.
- [Field](https://hextaui.com/docs/field) - Labels, descriptions and errors wired to their control, with validation states and layouts for forms.
- [Input](https://hextaui.com/docs/input) - A text input with three sizes, invalid and read-only states, native validation styling and a 16px touch font so phones never zoom in.
- [Input group](https://hextaui.com/docs/input-group) - An input with icons, text, buttons or a keyboard hint attached, sharing one border and focus ring.
- [Native select](https://hextaui.com/docs/native-select) - The browser's own select, styled to match Input, with a quiet placeholder, Field support and the OS picker on every device.
- [Radio group](https://hextaui.com/docs/radio-group) - Pick one option from a set, with a dot that hands off between choices and cards whose selection ring slides to the new pick.
- [Spinner](https://hextaui.com/docs/spinner) - A loading indicator with Apple-style ticks or a breathing ring that can wait before showing and stay long enough not to flicker.

## Code

11 files, added to components/blocks/address-form.
