Shipping Address
Native address fields with system autofill, configurable regional requirements, and recoverable submission.
Install
First install? Set up the registry in your app.
npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add shipping-addressSource files
Expand a file to read the source the installer copies into your app.
components/blocks/shipping-address/ShippingAddress.tsx
import * as React from 'react'
import { TextInput, View, useWindowDimensions, type ViewProps } from 'react-native'
import { Button } from '@/components/ui/button'
import { FormField } from '@/components/ui/form-field'
import { Input, type InputProps } from '@/components/ui/input'
import { Text } from '@/components/ui/text'
import { useAnnouncement } from '@/lib/accessibility'
import { renderTextChildren } from '@/lib/label-children'
import { cn } from '@/lib/utils'
export interface ShippingAddressValue {
name: string
line1: string
line2: string
city: string
region: string
postalCode: string
}
type Field = keyof ShippingAddressValue
type FieldErrors = Partial<Record<Field, string>>
export interface ShippingAddressProps extends Omit<ViewProps, 'children'> {
className?: string
title?: string
value?: ShippingAddressValue
defaultValue?: ShippingAddressValue
onFieldChange?: (field: Field, draft: string) => void
onSubmit?: (address: ShippingAddressValue) => void | boolean | Promise<void | boolean>
validate?: (address: ShippingAddressValue) => FieldErrors
regionRequired?: boolean
postalCodeRequired?: boolean
countryField?: React.ReactNode | ((props: { disabled: boolean }) => React.ReactNode)
labels?: Partial<Record<Field, string>>
requiredMessage?: (label: string) => string
validationSummary?: string
failedMessage?: string
submitLabel?: string
}
const empty: ShippingAddressValue = { name: '', line1: '', line2: '', city: '', region: '', postalCode: '' }
const fieldLabels: Record<Field, string> = {
name: 'Recipient name',
line1: 'Street address',
line2: 'Apartment or unit',
city: 'City or town',
region: 'State, province, or region',
postalCode: 'Postal code',
}
const fields: Field[] = ['name', 'line1', 'line2', 'city', 'region', 'postalCode']
export function ShippingAddress({
className,
title = 'Delivery address',
value,
defaultValue = empty,
onFieldChange,
onSubmit,
validate,
regionRequired = false,
postalCodeRequired = false,
countryField,
labels,
requiredMessage = (label) => `Enter ${label.toLocaleLowerCase()}.`,
validationSummary = 'Check the highlighted address fields.',
failedMessage = 'We couldn’t save this address. Try again.',
submitLabel = 'Use this address',
...props
}: ShippingAddressProps) {
const { width, fontScale } = useWindowDimensions()
const [internal, setInternal] = React.useState(defaultValue)
const draft = React.useRef(defaultValue)
const [errors, setErrors] = React.useState<FieldErrors>({})
const [firstError, setFirstError] = React.useState<{ field: Field }>()
const [failed, setFailed] = React.useState(false)
const [busy, setBusy] = React.useState(false)
const submitting = React.useRef(false)
const inputs = React.useRef<Partial<Record<Field, React.ComponentRef<typeof TextInput> | null>>>({})
const shown = value ?? internal
const copy = { ...fieldLabels, ...labels }
const required: Field[] = ['name', 'line1', 'city']
if (regionRequired) required.push('region')
if (postalCodeRequired) required.push('postalCode')
const validationIssue = fields.some((field) => Boolean(errors[field]))
useAnnouncement(failed ? failedMessage : validationIssue ? validationSummary : undefined)
React.useEffect(() => {
if (firstError) inputs.current[firstError.field]?.focus()
}, [firstError])
async function submit(finalPostalCode?: string) {
if (submitting.current || !onSubmit) return
if (value === undefined && finalPostalCode !== undefined && finalPostalCode !== draft.current.postalCode) {
draft.current = { ...draft.current, postalCode: finalPostalCode }
setInternal(draft.current)
onFieldChange?.('postalCode', finalPostalCode)
}
const current = value ?? draft.current
const address = {
name: current.name.trim(),
line1: current.line1.trim(),
line2: current.line2.trim(),
city: current.city.trim(),
region: current.region.trim(),
postalCode: current.postalCode.trim(),
}
const nextErrors = { ...validate?.(address) }
for (const field of required) {
if (!address[field]) nextErrors[field] = requiredMessage(copy[field])
}
const first = fields.find((field) => Boolean(nextErrors[field]))
setErrors(nextErrors)
setFirstError(first ? { field: first } : undefined)
setFailed(false)
if (first) return
submitting.current = true
setBusy(true)
try {
if ((await onSubmit(address)) === false) setFailed(true)
} catch {
setFailed(true)
} finally {
submitting.current = false
setBusy(false)
}
}
function field(key: Field, autoComplete: InputProps['autoComplete'], next?: Field) {
return (
<FormField label={copy[key]} required={required.includes(key)} error={errors[key]} announceError={false}>
{(control) => (
<Input
{...control}
ref={(input) => {
inputs.current[key] = input
}}
value={shown[key]}
editable={!busy}
autoComplete={autoComplete}
autoCapitalize={key === 'postalCode' ? 'characters' : 'words'}
autoCorrect={false}
returnKeyType={next ? 'next' : 'done'}
submitBehavior={next ? 'submit' : 'blurAndSubmit'}
onSubmitEditing={(event) => {
if (next) inputs.current[next]?.focus()
else void submit(event.nativeEvent.text)
}}
onChangeText={(text) => {
if (submitting.current) return
if (value === undefined) {
draft.current = { ...draft.current, [key]: text }
setInternal(draft.current)
}
onFieldChange?.(key, text)
if (errors[key]) setErrors((current) => ({ ...current, [key]: undefined }))
if (firstError?.field === key) setFirstError(undefined)
if (failed) setFailed(false)
}}
/>
)}
</FormField>
)
}
const compact = width < 390 || fontScale >= 1.4
return (
<View {...props} className={cn('gap-4', className)}>
<Text size="title" accessibilityRole="header">
{title}
</Text>
{renderTextChildren(typeof countryField === 'function' ? countryField({ disabled: busy }) : countryField)}
{field('name', 'name', 'line1')}
{field('line1', 'address-line1', 'line2')}
{field('line2', 'address-line2', 'city')}
{field('city', 'postal-address-locality', 'region')}
<View className={cn('gap-4', !compact && 'flex-row items-start')}>
<View className={cn(!compact && 'min-w-0 flex-1')}>
{field('region', 'postal-address-region', 'postalCode')}
</View>
<View className={cn(!compact && 'min-w-0 flex-1')}>{field('postalCode', 'postal-code')}</View>
</View>
{failed || validationIssue ? (
<Text size="sm" className="text-destructive">
{failed ? failedMessage : validationSummary}
</Text>
) : null}
{onSubmit ? (
<Button
accessibilityLabel={submitLabel}
loading={busy}
onPress={() => {
void submit()
}}
>
{submitLabel}
</Button>
) : null}
</View>
)
}
components/blocks/shipping-address/index.ts
export { ShippingAddress, type ShippingAddressProps, type ShippingAddressValue } from './ShippingAddress'