# Reusable field components

> Write an input component once, register it, and use it on every form by name.

Source: https://forms.lunarhue.dev/react/composition/field-components

A component that takes a field, like the ones in [Fields](https://forms.lunarhue.dev/react/basics/fields.md),
can be registered on `createForms`. Every form from it then has the component
as a member, `form.TextField`, that takes a field name instead of the `field`
prop. Still no plugins.

```tsx title="profile.tsx"
import { createForms, useForm } from "@lunarhue/forms-react";
import { CheckboxField, NumberField, TextField } from "./fields";

// Registered once. Every form from `forms` gets `form.TextField` and the rest.
const forms = createForms({ fields: { TextField, NumberField, CheckboxField } });

interface Profile {
  name: string;
  nickname?: string;
  age: number | undefined;
  newsletter: boolean;
}

const profile = forms.define<Profile>({
  defaultValues: { name: "", age: undefined, newsletter: false },
  validate: {
    fields: {
      age: (age) => (age === undefined || age < 18 ? { message: "You must be 18 or over." } : undefined),
    },
  },
  onSubmit: (value) => value,
});

export default function ProfileForm() {
  const form = useForm(profile, { id: "profile" });
  return (
    <form.Form>
      {(formProps) => (
        <form {...formProps}>
          <form.TextField
            name="name"
            label="Name"
            validate={(name) => (name ? undefined : { message: "Enter your name." })}
          />
          <form.TextField name="nickname" label="Nickname (optional)" />
          <form.NumberField name="age" label="Age" />
          <form.CheckboxField name="newsletter" label="Send me the newsletter" />
          <button type="submit">Save</button>
        </form>
      )}
    </form.Form>
  );
}
```

```tsx title="fields.tsx"
import { type FieldApi, type FormError, inputProps } from "@lunarhue/forms-react";

function Errors({ id, errors }: { readonly id: string; readonly errors: readonly FormError[] }) {
  return (
    <ul id={id}>
      {errors.map((error) => (
        <li key={error.message}>{error.message}</li>
      ))}
    </ul>
  );
}

// `undefined` in the type lets it take optional string fields too.
export function TextField({ field, label }: { field: FieldApi<string | undefined>; label: string }) {
  return (
    <div>
      <label htmlFor={field.id}>{label}</label>
      <input {...inputProps(field)} />
      <Errors id={field.errorId} errors={field.shownErrors} />
    </div>
  );
}

// Only number fields fit, so `<form.NumberField name="name" />` is a type error.
export function NumberField({ field, label }: { field: FieldApi<number>; label: string }) {
  return (
    <div>
      <label htmlFor={field.id}>{label}</label>
      <input {...inputProps(field, { kind: "number" })} />
      <Errors id={field.errorId} errors={field.shownErrors} />
    </div>
  );
}

export function CheckboxField({ field, label }: { field: FieldApi<boolean>; label: string }) {
  return (
    <div>
      <label>
        <input {...inputProps(field, { kind: "checkbox" })} />
        {label}
      </label>
      <Errors id={field.errorId} errors={field.shownErrors} />
    </div>
  );
}
```

## Registering a component

Type the prop as `FieldApi<T>`, where `T` is the value type the component
edits, and list the component under `fields`:

```tsx
import { createForms, type FieldApi, inputProps } from "@lunarhue/forms-react";

function TextField({ field, label }: { field: FieldApi<string>; label: string }) {
  return (
    <label>
      {label}
      <input {...inputProps(field)} />
    </label>
  );
}

export const forms = createForms({ fields: { TextField } });
```

Make `forms` once and import it wherever you define a form.

## Using it

`form.TextField` takes the component's own props, minus `field`, plus one of:

- `name`, a field name such as `"address.city"`. The compiler checks it, and
  accepts only names whose value fits the component: a `FieldApi<string>`
  component won't take a number field. See
  [Typed names and handles](https://forms.lunarhue.dev/react/composition/typed-paths.md).
- `handle`, a field handle from `form.root.at(...)` or an array row.

```tsx
<form.TextField name="name" label="Name" />
<form.NumberField name="age" label="Age" />
```

It also takes `validate`, which adds a validator while it is mounted, as on
`form.Field`:

```tsx
<form.TextField name="name" label="Name" validate={(name) => (name ? undefined : { message: "Enter your name." })} />
```

## Optional fields

A `FieldApi<string>` component takes required string fields only. An optional
field such as `nickname?: string` starts out `undefined`, and a component that
reads `field.value` as a `string` would get it wrong. To render optional
fields too, put `undefined` in the type:

```tsx
function TextField({ field, label }: { field: FieldApi<string | undefined>; label: string }) {
  return (
    <label>
      {label}
      <input {...inputProps(field)} />
    </label>
  );
}
```

This component takes `name: string` and `nickname?: string` alike. A checkbox
does the same with `FieldApi<boolean | undefined>`. `null` works the same way:
`FieldApi<string | null>` takes `string` and `string | null` fields.

The type checker doesn't stop such a component from writing `undefined` into
a required field, so leave writes to `inputProps` or write a value of the
field's own type. A `FieldApi<number>` component has the same gap, since its
`value` is `number | undefined`.

## Field types

`defineField(component)` makes a field type, and `fields` takes one where it
takes a component:

```ts
const NameField = defineField(TextField);

const forms = createForms({ fields: { TextField, NameField } });
```

With no other arguments it renders the same as `TextField`. The arguments
after the component are plugin parts that every field it renders gets, such
as a mask on a phone input. See
[Parts on field components](https://forms.lunarhue.dev/react/plugin-composition/field-parts.md).
