# useField

Connects a custom control to the Field around it: its labels, description, error and state.

Source: [use-field.ts](https://github.com/jakejarvis/jarvis-ui/blob/main/src/hooks/use-field.ts)

```tsx
"use client";

import { StarIcon } from "lucide-react";
import * as React from "react";

import { Field, FieldControl, FieldDescription, FieldLabel } from "@/components/ui/field";
import { useField, useFieldLabels } from "@/hooks/use-field";

function Rating({ name }: { name?: string }) {
  const ref = React.useRef<HTMLDivElement>(null);
  const [value, setValue] = React.useState(0);
  const field = useField();
  const { labelledBy } = useFieldLabels(ref);

  return (
    <div
      ref={ref}
      role="radiogroup"
      aria-labelledby={labelledBy}
      aria-describedby={field.describedBy}
      aria-invalid={field.invalid || undefined}
      aria-disabled={field.disabled || undefined}
      className="relative -mx-1 flex"
    >
      {[1, 2, 3, 4, 5].map((star) => (
        <button
          key={star}
          type="button"
          role="radio"
          aria-checked={value === star}
          aria-label={star === 1 ? "1 star" : `${star} stars`}
          data-filled={star <= value || undefined}
          disabled={field.disabled}
          onClick={() => setValue(star)}
          className="flex size-7 cursor-pointer items-center justify-center rounded-sm text-icon-muted transition-colors hover:text-icon focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:cursor-not-allowed data-filled:text-warning [&_svg]:size-5"
        >
          <StarIcon fill={star <= value ? "currentColor" : "none"} />
        </button>
      ))}
      <FieldControl
        name={name}
        value={value || ""}
        readOnly
        tabIndex={-1}
        aria-hidden="true"
        className="pointer-events-none absolute size-px opacity-0"
        onFocus={() => ref.current?.querySelector("button")?.focus()}
      />
    </div>
  );
}

export default function UseFieldRating() {
  return (
    <Field className="w-60">
      <FieldLabel>Rating</FieldLabel>
      <Rating name="rating" />
      <FieldDescription>How was your stay?</FieldDescription>
    </Field>
  );
}
```

## Installation

Add the registry, once per project:

```bash
npx shadcn@latest registry add @jarvis=https://ui.jarv.is/r/{name}.json
```

Then add the hook:

```bash
npx shadcn@latest add @jarvis/use-field
```

## Usage

```tsx
"use client";

import * as React from "react";

import { FieldControl } from "@/components/ui/field";
import { useField, useFieldLabels } from "@/hooks/use-field";

export function Rating({ name }: { name?: string }) {
  const ref = React.useRef<HTMLDivElement>(null);
  const [value, setValue] = React.useState(0);
  const field = useField();
  const { labelledBy } = useFieldLabels(ref);

  return (
    <div
      ref={ref}
      role="radiogroup"
      aria-labelledby={labelledBy}
      aria-describedby={field.describedBy}
      aria-invalid={field.invalid || undefined}
      aria-disabled={field.disabled || undefined}
      className="relative flex gap-1"
    >
      {[1, 2, 3, 4, 5].map((star) => (
        <button
          key={star}
          type="button"
          role="radio"
          aria-checked={value === star}
          aria-label={star === 1 ? "1 star" : `${star} stars`}
          disabled={field.disabled}
          onClick={() => setValue(star)}
        >
          {star <= value ? "★" : "☆"}
        </button>
      ))}
      <FieldControl
        name={name}
        value={value || ""}
        readOnly
        tabIndex={-1}
        aria-hidden="true"
        className="pointer-events-none absolute size-px opacity-0"
        onFocus={() => ref.current?.querySelector("button")?.focus()}
      />
    </div>
  );
}
```

A [Field](https://ui.jarv.is/components/field.md) links its label, description and error to the controls Base UI
provides. A control of your own, such as a group of radio-like buttons or a canvas, connects to the
field with these hooks. [Date Picker](https://ui.jarv.is/components/date-picker.md), [Tag Input](https://ui.jarv.is/components/tag-input.md)
and the other custom controls use them the same way.

`useField` reads the `Field` around the component. It returns the `id`s of the field's description
and error, for `aria-describedby`, and whether the field is `invalid` or `disabled`.
`useFieldLabels` returns the `id` of the field's `FieldLabel`, for `aria-labelledby`, so a plain
`<FieldLabel>` with no `htmlFor` labels the radio group. Both hooks read the state that Base UI's
Field keeps, so they stay current when a label, message or state changes later. Outside a `Field`,
`useField` returns no `describedBy` and `false` for `invalid` and `disabled`.

A field labelled by a plain `<label>` rather than a `FieldLabel` has no label in that state. In that
case, `useFieldLabels` reads labels from the DOM: the ones its `labels` option returns, such as a
hidden input's `labels`, or else the labels of `target` itself, when `target` is an element that
can have labels. It gives each label an `id` if it has none, and watches the field for labels that
change later.

Base UI registers the description, error and label in effects, so the server render has no
`aria-describedby` or `aria-labelledby`. It does have `invalid` and `disabled`.

The hidden `FieldControl` in the example submits the value with a form, takes part in the field's
validation, and passes focus to the control when its label is clicked. Every `FieldControl` in a
field takes the `id` that its label points at. When a field holds two custom controls, such as a
date and a time, `useFieldControlId` gives the second one an `id` of its own.

## API

### useField

`useField()` takes no arguments. It reads the `Field` that the component renders in, and returns:

| Value         | Type                  | Description                                                                           |
| ------------- | --------------------- | ------------------------------------------------------------------------------------- |
| `describedBy` | `string \| undefined` | The `id`s of the field's description and error, for the control's `aria-describedby`. |
| `invalid`     | `boolean`             | Whether the field is invalid.                                                         |
| `disabled`    | `boolean`             | Whether the field is disabled.                                                        |

### useFieldLabels

`useFieldLabels(target, options?)` takes the control, as a ref or the element itself, and these
options. It reads the control's labels when the field has no `FieldLabel`.

| Option     | Type                                                                                     | Default | Description                                                                                                                                                                                                                                                                                                               |
| ---------- | ---------------------------------------------------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `labels?`  | `(() => Iterable<HTMLLabelElement> \| ArrayLike<HTMLLabelElement> \| null \| undefined)` | —       | Returns the control's labels, such as a hidden input's `labels`, for a field without a `FieldLabel`. It's called once the control mounts, and again whenever a label, `for` or `id` inside the field changes. Without it, the hook reads the labels of `target` itself, when `target` is an element that can have labels. |
| `enabled?` | `boolean`                                                                                | `true`  | Whether to watch the labels. While it's `false`, the hook returns `undefined`, such as when the control has an `aria-label`.                                                                                                                                                                                              |

It returns:

| Value        | Type                  | Description                                                                                                            |
| ------------ | --------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `labelledBy` | `string \| undefined` | The `id`s of the labels, separated by spaces, for the control's `aria-labelledby`, or `undefined` when there are none. |

### useFieldControlId

`useFieldControlId(target, options?)` takes the control's `FieldControl`, as a ref or the element
itself, and these options.

| Option | Type     | Default | Description                                                                                                     |
| ------ | -------- | ------- | --------------------------------------------------------------------------------------------------------------- |
| `id?`  | `string` | —       | The `id` to give the `FieldControl` when another control already has the field's. Without it, one is generated. |

It returns the `id` to give the `FieldControl`:

| Value | Type                  | Description                                                                                                                        |
| ----- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `id`  | `string \| undefined` | The `id` for the `FieldControl`: `undefined` while it can keep the field's, or its own once another control in the field has that. |

The file also exports `FieldTarget`, the type of `target`: a ref or an element.
