# Upload Field (https://s3.dimah.dev/docs/ui/components/upload-field)

Add file uploads to a form. Each file that uploads through `UploadField` adds
its object key to the field's value, and every key submits as a hidden
`<input name>`. Put the [Upload](https://s3.dimah.dev/docs/ui/components/upload) parts inside it.

```tsx title="upload-field-demo.tsx"
"use client";

import { useState, type FormEvent } from "react";
import { useUpload } from "@dimah-s3/react";
import {
  UploadDropzone,
  UploadField,
  UploadFieldValue,
  UploadToasts,
} from "@dimah-s3/ui";
import { Button } from "@/components/ui/button";

const MAX_FILES = 3;

export function UploadFieldDemo() {
  const upload = useUpload({
    route: "uploads",
    maxFiles: MAX_FILES,
    maxFileSize: 75 * 1024 * 1024,
  });
  const [submitted, setSubmitted] = useState<string[] | null>(null);

  function onSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const form = new FormData(event.currentTarget);
    setSubmitted(form.getAll("attachments").map(String));
  }

  return (
    <form
      className="mx-auto flex w-full max-w-md flex-col gap-3"
      onSubmit={onSubmit}
    >
      <UploadField upload={upload} name="attachments" maxFiles={MAX_FILES}>
        {/* Progress shows inside the dropzone; the value lists the keys. */}
        <UploadDropzone />
        <UploadFieldValue />
      </UploadField>
      <UploadToasts upload={upload} />
      <Button type="submit" className="w-fit" disabled={upload.isPending}>
        Submit
      </Button>
      {submitted ? (
        <output className="text-sm break-all text-muted-foreground">
          {submitted.length > 0
            ? `attachments: ${submitted.join(", ")}`
            : "No files attached."}
        </output>
      ) : null}
    </form>
  );
}
```

## Installation [#installation]

<Tabs items={["npm","shadcn"]}>
<Tab value="npm">
```tsx
import { UploadField, UploadFieldValue } from "@dimah-s3/ui";
```
</Tab>

<Tab value="shadcn">
```npm
npx shadcn@latest add @dimah-s3/upload-field
```

Adds `@/components/dimah-s3/upload/upload-field` and the upload family it
uses.
</Tab>
</Tabs>

Complete [Installation](https://s3.dimah.dev/docs/ui/installation) first: the package or registry
setup, the stylesheet, and one `<Toaster />` in your layout.

## Usage [#usage]

```tsx
"use client";

import { useUpload } from "@dimah-s3/react";
import {
  UploadDropzone,
  UploadField,
  UploadFieldValue,
  UploadToasts,
} from "@dimah-s3/ui";

export function TicketForm({
  save,
}: {
  save: (formData: FormData) => void | Promise<void>;
}) {
  const upload = useUpload({ route: "attachments", maxFiles: 5 });

  return (
    <form action={save} className="space-y-4">
      <UploadField upload={upload} name="attachments" maxFiles={5}>
        <UploadDropzone />
        <UploadFieldValue />
      </UploadField>
      <UploadToasts upload={upload} />
      <button type="submit">Send</button>
    </form>
  );
}
```

On the server, read the keys with `formData.getAll("attachments")`.

<Callout type="warn">
`maxFiles` and the value are client-side. Check the keys, their count, and who
owns them in your own endpoint. See [Forms](https://s3.dimah.dev/docs/react/forms).
</Callout>

## Anatomy [#anatomy]

```tsx
<UploadField upload={upload} name="attachments">
  <UploadTrigger /> {/* or UploadDropzone */}
  <UploadStatus />
  <UploadFieldValue />
</UploadField>
```

`UploadField` is an [`Upload`](https://s3.dimah.dev/docs/ui/components/upload) root, so every
upload part works inside it. Uploaded files move from the status to
`UploadFieldValue`.

## Examples [#examples]

### Attach button [#attach-button]

A message form with an attach button, a saved key as `defaultValue`, and
`UploadStatus` for the files in flight.

```tsx title="upload-field-button-demo.tsx"
"use client";

import { useState, type FormEvent } from "react";
import { PaperclipIcon } from "lucide-react";
import { useUpload } from "@dimah-s3/react";
import {
  UploadField,
  UploadFieldValue,
  UploadStatus,
  UploadToasts,
  UploadTrigger,
} from "@dimah-s3/ui";
import { Button } from "@/components/ui/button";

/** Keys saved with the ticket earlier. They show without an upload. */
const SAVED_KEYS = ["uploads/7f3c2a90/invoice-0042.pdf"];

export function UploadFieldButtonDemo() {
  const upload = useUpload({
    route: "uploads",
    maxFiles: 3,
    maxFileSize: 75 * 1024 * 1024,
  });
  const [submitted, setSubmitted] = useState<string[] | null>(null);

  function onSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const form = new FormData(event.currentTarget);
    setSubmitted(form.getAll("files").map(String));
  }

  return (
    <form
      className="mx-auto flex w-full max-w-md flex-col gap-3 rounded-xl border p-4"
      onSubmit={onSubmit}
    >
      <label className="flex flex-col gap-1.5 text-sm font-medium">
        Message
        <textarea
          name="message"
          rows={3}
          defaultValue="The invoice total looks wrong."
          className="rounded-md border bg-transparent px-3 py-2 font-normal outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
        />
      </label>
      <UploadField
        upload={upload}
        name="files"
        maxFiles={3}
        defaultValue={SAVED_KEYS}
      >
        <UploadFieldValue />
        <UploadStatus />
        <div className="flex items-center justify-between gap-2">
          <UploadTrigger variant="ghost" size="sm">
            <PaperclipIcon data-icon="inline-start" />
            Attach files
          </UploadTrigger>
          <Button type="submit" size="sm" disabled={upload.isPending}>
            Send
          </Button>
        </div>
      </UploadField>
      <UploadToasts upload={upload} />
      {submitted ? (
        <output className="text-xs break-all text-muted-foreground">
          files: {submitted.join(", ") || "none"}
        </output>
      ) : null}
    </form>
  );
}
```

### Controlled value [#controlled-value]

Keep the keys in your own state with `value` and `onValueChange`.

```tsx
const [keys, setKeys] = useState<string[]>(post.attachmentKeys);

<UploadField
  upload={upload}
  name="attachments"
  value={keys}
  onValueChange={setKeys}
>
  <UploadTrigger />
  <UploadFieldValue />
</UploadField>;
```

### Custom value rows [#custom-value-rows]

Pass a function to `UploadFieldValue` to render each key.

```tsx
function AttachmentNames() {
  const { remove } = useUploadFieldContext();

  return (
    <UploadFieldValue>
      {(item) => (
        <span>
          {item.fileName}
          <button type="button" onClick={() => remove(item.key)}>
            Remove
          </button>
        </span>
      )}
    </UploadFieldValue>
  );
}
```

## Value [#value]

- A file adds its key once it uploads. Failed and cancelled files add nothing.
- New picks append; they never cancel files still uploading.
- Removing a key does not delete the stored object.

## Limit [#limit]

With `maxFiles`, the field takes only the files that still fit and rejects
the rest with `TOO_MANY_FILES`. The limit holds for every upload through the
hook, not only the field's own parts. When other code also uploads through it,
pass `append: true` to `useUpload`.

Read `useUploadContext().isFull` to show your own hint when it is full:

```tsx
function FullHint() {
  const { isFull } = useUploadContext();
  return isFull ? <p>Remove a file to add another.</p> : null;
}
```

## Form reset [#form-reset]

An uncontrolled field goes back to `defaultValue` when its form resets,
including React's reset after a `<form action>`. Call `upload.reset()` to
clear the status too. A controlled field resets `value` itself.

## API Reference [#api-reference]

### UploadField [#uploadfield]

| Prop            | Type                       | Default  | Description                                                   |
| --------------- | -------------------------- | -------- | ------------------------------------------------------------- |
| `upload`        | `UseUploadReturn`          | required | The `useUpload` return whose uploads fill the field           |
| `name`          | `string`                   | required | Form field name. Each key submits as its own hidden input     |
| `value`         | `readonly string[]`        | —        | Object keys, when you control the value                       |
| `defaultValue`  | `readonly string[]`        | —        | Object keys to start with, when the field keeps its own value |
| `onValueChange` | `(keys: string[]) => void` | —        | Runs with the new keys after one is added or removed          |
| `maxFiles`      | `number`                   | —        | Most keys the field holds, across every call on the hook      |
| `children`      | `ReactNode`                | required | Upload parts and `UploadFieldValue`                           |

### UploadFieldValue [#uploadfieldvalue]

Also accepts every `ul` prop except `children`.

| Prop       | Type                                   | Default                        | Description     |
| ---------- | -------------------------------------- | ------------------------------ | --------------- |
| `children` | `(item: UploadFieldItem) => ReactNode` | File card with a remove action | Renders one key |

### useUploadFieldContext [#useuploadfieldcontext]

Returns the field's state inside `UploadField`.

| Property    | Type                         | Description                                                     |
| ----------- | ---------------------------- | --------------------------------------------------------------- |
| `name`      | `string`                     | The field name                                                  |
| `value`     | `readonly string[]`          | The keys                                                        |
| `items`     | `readonly UploadFieldItem[]` | The keys with `fileName`, `fileSize`, `contentType`, and `file` |
| `remaining` | `number \| null`             | Files that still fit, or `null` without `maxFiles`              |
| `remove`    | `(key: string) => void`      | Drops a key from the value. The stored object is kept           |