# useFormField
Package: @mantine/hooks
Import: import { useFormField } from '@mantine/hooks';

## Usage

`use-form-field` subscribes a custom input to a form field through its `onChange` handler.
A state manager such as `useForm` attaches a field to the handler it passes down.
The input then rerenders on its own when the field value changes, the component that owns the form does not.

Pass the `onChange` prop to the hook. When a field is attached, `field.subscribed` is `true`
and the component must render `field.value`. Otherwise, keep using the `value` prop:

```tsx
import { useFormField } from '@mantine/hooks';

interface CustomInputProps {
  value?: string;
  onChange?: (value: string) => void;
}

function CustomInput({ value, onChange }: CustomInputProps) {
  const field = useFormField<string>(onChange);
  const currentValue = field.subscribed ? field.value : value;

  return (
    <input
      value={currentValue ?? ''}
      onChange={(event) => onChange?.(event.currentTarget.value)}
    />
  );
}
```

All Mantine inputs and components built with [use-uncontrolled](https://alpha.mantine.dev/llms/hooks-use-uncontrolled.md) already call this hook.

## Field protocol

A handler carries a field when a `FormField` object is stored on it under `Symbol.for('mantine-form-field')`.
Any store can attach it:

```tsx
import { FormField } from '@mantine/hooks';

const FORM_FIELD = Symbol.for('mantine-form-field');

function attachField<Handler extends (...args: any[]) => any>(
  handler: Handler,
  field: FormField
) {
  (handler as any)[FORM_FIELD] = field;
  return handler;
}
```

## onExternalWrite

Some components keep state that the value cannot express. A date input with a partially typed date
reports `null` until the date is complete. When the store writes `null` again, the value does not
change and the component cannot know that it has to clear the entry.

`onExternalWrite` is called with the field value on every write made by the store, not by the component.
It is also called when the component is bound to another field, for example after list items are reordered.
Update only the internal state in the callback, do not call `onChange`:

```tsx
import { useState } from 'react';
import { useFormField } from '@mantine/hooks';

interface ExpiryInputProps {
  value?: string;
  onChange?: (value: string) => void;
}

function splitExpiry(value: string | undefined) {
  const [month = '', year = ''] = (value || '').split('/');
  return { month, year };
}

function ExpiryInput({ value, onChange }: ExpiryInputProps) {
  const [parts, setParts] = useState(() => splitExpiry(value));

  useFormField<string>(onChange, {
    subscribe: false,
    onExternalWrite: (external) => setParts(splitExpiry(external)),
  });

  const handleChange = (next: { month: string; year: string }) => {
    setParts(next);
    const complete = next.month.length === 2 && next.year.length === 2;
    onChange?.(complete ? `${next.month}/${next.year}` : '');
  };

  return (
    <div>
      <input
        placeholder="MM"
        value={parts.month}
        onChange={(event) => handleChange({ ...parts, month: event.currentTarget.value })}
      />
      <input
        placeholder="YY"
        value={parts.year}
        onChange={(event) => handleChange({ ...parts, year: event.currentTarget.value })}
      />
    </div>
  );
}
```

Set `subscribe: false` when the component renders the `value` prop instead of the subscribed value.
The store then rerenders the component that passes `value`.

## Definition

```tsx
interface UseFormFieldOptions<Value = any> {
  /** If set, the component is subscribed to the field value and must render the returned `value` instead of the `value` prop, `true` by default */
  subscribe?: boolean;

  /** Called with the field value when the store writes it and when the component is bound to another field. Not called for changes reported by the component itself. Must not call `onChange`. */
  onExternalWrite?: (value: Value) => void;
}

interface UseFormFieldReturnValue<Value = any> {
  /** `true` if the handler carries a field */
  bound: boolean;

  /** `true` if the component is subscribed to the field value and must render `value` */
  subscribed: boolean;

  /** Path of the field in the store, `null` if the component is not bound */
  path: string | null;

  /** Current field value, `undefined` if the component is not subscribed */
  value: Value | undefined;
}

function useFormField<Value = any>(
  onChange: unknown,
  options?: UseFormFieldOptions<Value>
): UseFormFieldReturnValue<Value>;
```

## Exported types

The `UseFormFieldOptions`, `UseFormFieldReturnValue` and `FormField` types are exported from `@mantine/hooks`:

```tsx
import type { UseFormFieldOptions, UseFormFieldReturnValue, FormField } from '@mantine/hooks';
```

## Usage with @mantine/form

[use-form](https://alpha.mantine.dev/llms/form-use-form.md) attaches a field to every `onChange` handler returned by `getInputProps`.
A custom input that calls `use-form-field` rerenders alone when its field changes.
Writes made with form methods, for example `form.setFieldValue` or `form.reset`, reach `onExternalWrite`.
With `subscribe: false`, the form rerenders the component that called `useForm` instead,
so the input receives a new `value` prop:

```tsx
import { useForm } from '@mantine/form';
import { CustomInput } from './CustomInput';

function Demo() {
  const form = useForm({ initialValues: { name: '' } });

  // CustomInput calls useFormField(onChange) and rerenders alone
  return <CustomInput {...form.getInputProps('name')} />;
}
```

In uncontrolled mode, bind each field path to a single input. A component that is not subscribed
does not update while the user types in a subscribed input of the same path.
See [one input per field path](https://alpha.mantine.dev/llms/form-uncontrolled.md#one-input-per-field-path).

See the [custom input](https://mantine.dev/form/examples/CustomInputSubscription) and
[rich text](https://mantine.dev/form/examples/RichTextForm) form examples.
