UIPackage React Native
Search
Menu

Form Field

Persistent field labels, instructions, required state, and announced validation errors. A render function connects native accessibility props to the caller-owned control.

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 form-field

Source files

Expand a file to read the source the installer copies into your app.

components/ui/form-field/FormField.tsx
import * as React from 'react'
import { View, type AccessibilityProps, type ViewProps } from 'react-native'
import { Text } from '@/components/ui/text'
import { useAnnouncement } from '@/lib/accessibility'
import { cn } from '@/lib/utils'

export interface FormFieldControlProps extends AccessibilityProps {
  nativeID: string
  invalid: boolean
}

export interface FormFieldProps extends Omit<ViewProps, 'children'> {
  label: string
  description?: string
  error?: string
  announceError?: boolean
  required?: boolean
  className?: string
  /** Spread these props onto the field. Its value, handlers, and ref stay with the caller. */
  children: (props: FormFieldControlProps) => React.ReactNode
}

const FormField = React.forwardRef<React.ComponentRef<typeof View>, FormFieldProps>(
  ({ label, description, error, announceError = true, required, className, children, ...props }, ref) => {
    const id = React.useId()
    useAnnouncement(error && announceError ? `${label}. ${error}` : undefined)
    const hint = [description, error].filter(Boolean).join(' ')
    return (
      <View ref={ref} {...props} className={cn('gap-2', className)}>
        <Text size="sm" className="font-medium">
          {label}
          {required ? ' (required)' : ''}
        </Text>
        {description ? (
          <Text size="sm" variant="muted">
            {description}
          </Text>
        ) : null}
        {children({
          nativeID: `field-${id}`,
          accessibilityLabel: required ? `${label}, required` : label,
          accessibilityHint: hint || undefined,
          invalid: !!error,
        })}
        {error ? (
          <Text size="sm" className="text-destructive">
            {error}
          </Text>
        ) : null}
      </View>
    )
  },
)
FormField.displayName = 'FormField'

export { FormField }
components/ui/form-field/index.ts
export { FormField, type FormFieldProps, type FormFieldControlProps } from './FormField'

Dependencies

Registry items

Browse forms and selection