# Tag input

> The invite field, done properly: typed letters grow a chip round themselves, pasted lists spill out of the caret, and a duplicate flies into its twin.

Most tag inputs swap the text you typed for a chip that pops in somewhere else, jump a whole line when one is removed and quietly drop duplicates. Here the letters you typed stay exactly where they were while a hairline shell grows round them. Paste a list and it spills out of the caret chip by chip: a repeat flies into the chip it repeats, which bumps to say so, and an address that isn't one lands red and shakes. When resolve() knows an address, "maya@fernhill.co" morphs into "Maya Chen" as her initials open in. Picking a suggestion carries its name from the list into its chip. Backspace in an empty field selects the last chip, and again (or a second click on any chip) drops its shell so the letters are text you can edit. Every chip glides when one leaves or a line wraps, the field's height eases to fit, and out of focus the lines past the second fold into a rolling "+4".

## Install

```bash
npx shadcn@latest add @hairline/tag-input
```

Needs React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

- npm: none
- Hairline UI components it needs (the CLI installs them too): `text-morph`, `number-roll`
- Docs and live preview: https://hairlineui.com/ui/tag-input
- Registry item (source): https://hairlineui.com/r/tag-input.json

## Usage

```tsx
import { TagInput, type TagInputTag } from "@/components/tag-input";

const [tags, setTags] = useState<TagInputTag[]>([]);

<TagInput
  value={tags}
  onValueChange={setTags}
  label="Invite by email"
  placeholder="Names or emails"
  separators={/[\s,;]+/}
  normalize={(v) => v.toLowerCase()}
  validate={(v) => (/^\S+@\S+\.\S+$/.test(v) ? null : `“${v}” isn’t an email address`)}
/>
```

## Invite teammates from your directory

suggestions searches your members as you type, resolve turns a typed address into a person once it's added, and max keeps the field to the seats the plan has left. Only tags without an error are sent.

```tsx
"use client";
import { useState } from "react";
import { TagInput, type TagInputTag } from "@/components/tag-input";
import { StatusButton, type ActionStatus } from "@/components/status-button";

export function InviteMembers({ seatsLeft }: { seatsLeft: number }) {
  const [tags, setTags] = useState<TagInputTag[]>([]);
  const [status, setStatus] = useState<ActionStatus>("idle");
  const valid = tags.filter((t) => !t.error);

  return (
    <form
      onSubmit={async (e) => {
        e.preventDefault();
        setStatus("pending");
        const res = await fetch("/api/invites", { method: "POST", body: JSON.stringify(valid.map((t) => t.value)) });
        setStatus(res.ok ? "success" : "error");
        if (res.ok) setTags([]);
      }}
    >
      <TagInput
        value={tags}
        onValueChange={setTags}
        label="Invite by name or email"
        placeholder="Names or emails"
        separators={/[\s,;]+/}
        normalize={(v) => v.toLowerCase()}
        validate={(v) => (/^\S+@\S+\.\S+$/.test(v) ? null : `“${v}” isn’t an email address`)}
        suggestions={async (q) => {
          const res = await fetch(`/api/members?q=${encodeURIComponent(q)}`);
          return (await res.json()).map((m) => ({ value: m.email, label: m.name, image: m.avatarUrl, description: m.email }));
        }}
        resolve={async (email) => {
          const res = await fetch(`/api/members/lookup?email=${encodeURIComponent(email)}`);
          const m = res.ok ? await res.json() : null;
          return m && { label: m.name, image: m.avatarUrl };
        }}
        max={seatsLeft}
        limitMessage="No seats left on your plan"
        collapse={2}
      />
      <StatusButton type="submit" status={status} labels={{ idle: "Send invites", pending: "Sending", success: "Invites sent" }} disabled={!valid.length} />
    </form>
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `TagInputTag[]` | – | Controlled tags: { id, value, label?, image?, error? }. |
| `defaultValue` | `TagInputTag[]` | – | Starting tags when uncontrolled. |
| `onValueChange` | `(tags: TagInputTag[]) => void` | – | Every add, remove, edit and resolve. Tags with an error are included so you can show them; filter them out before sending. |
| `validate` | `(value: string) => string \| null` | – | Return a message to mark a value invalid. The chip turns red and the message shows under the field. |
| `resolve` | `(value: string) => Promise<{ label?, image? } \| null>` | – | Looks a value up once it's added. Return a label (and image) for the chip to morph into, or null to leave it. |
| `suggestions` | `TagInputSuggestion[] \| (query) => TagInputSuggestion[] \| Promise<…>` | – | A list to filter by value, label and description, or a function (which may be async) that finds matches. Values already added are left out. |
| `normalize` | `(value: string) => string` | – | Applied before checking and comparing, e.g. lower-casing addresses so duplicates are caught. |
| `separators` | `RegExp` | `/[,;\n]+/` | What splits typed and pasted text. Add \s for addresses. |
| `max` | `number` | – | How many tags the field takes. More shakes the field and shows limitMessage. |
| `limitMessage` | `string` | `"No room for more"` | The line shown when a value doesn't fit under max. |
| `createLabel` | `((text) => string) \| null` | `(t) => `Add “${t}”`` | The suggestion row that adds what's typed as it is. null hides it. |
| `collapse` | `number` | – | Lines to show while the field is out of focus; the rest fold into a "+N" count. |
| `label` | `string` | `"Add tags"` | Accessible name of the field and its list. |
| `placeholder` | `string` | – | Shown while the field is empty. |
| `hint` | `string` | – | A line under the field. Errors and notices take its place while they last. |
| `name` | `string` | – | Submits the valid values, comma-separated, with a form. |
| `disabled` | `boolean` | `false` | Nothing can be added, edited or removed. |
| `ref` | `Ref<TagInputHandle>` | – | paste(text), focus() and clear(), e.g. for a "Paste from spreadsheet" button or clearing after sending. |

## States

- **type**: Enter, Tab, a separator or leaving the field turns the text into a chip in place: its letters scale from the input's size to the chip's without moving, and the shell grows from their outline to the full pill in 480ms while the remove button scales in.
- **paste**: A pasted list (or one passed to the handle's paste) is split and each chip flies out of the caret 50ms after the last, from 0.86 scale and a 4px blur, 560ms each.
- **duplicate**: A value that's already there flies as a copy into its twin and dissolves as it arrives (a pasted one first turns up, in its turn, where it would have landed); the twin bumps to 1.08 with a slight overshoot and its ring flashes. The line under the field says "… is already here" for 2.6s.
- **invalid**: When validate() returns a message the chip lands with a red ring, an alert icon and a 380ms shake; the message stays under the field until the chip is fixed or removed.
- **resolve**: While resolve() runs the chip's icon slot shows a spinner; then the label morphs from the address to the name, the initials open in and the chip's shell eases to its new width while the chips after it glide.
- **pick**: Suggestions unfold from the field's edge; the highlight glides between rows. Choosing one carries its name from the row into its new chip in 480ms, where the chip's own letters take over.
- **edit**: Backspace or Enter on a chip, or a second click or tap on a selected one, shrinks its shell back round the letters and fades it; the address glides from where the chip was into the input with the caret at its end.
- **collapse**: With collapse set, leaving the field folds every line past that number: hidden chips fade through a blur, the field's height eases and a "+N" pill rolls in after the last chip that shows. Focus brings them back.

## What it handles

Most tag inputs swap the text you typed for a chip that pops in somewhere else, jump a line when one is removed and quietly drop duplicates. This one grows the chip around what you typed and tells people what happened to a pasted list.

- **Typed text becomes a chip in place**: The letters stay exactly where they were while a hairline shell grows around them.
- **Paste a list**: Pasted text is split on commas, semicolons and new lines (or your own pattern), and chips spill out of the caret one by one.
- **Duplicates and invalid values**: A repeat flies into the chip it repeats. An invalid value lands red, shakes and says why.
- **Addresses become names**: With resolve(), “maya@fernhill.co” morphs into “Maya Chen” as her initials open in.
- **Suggestions and limits**: Search suggestions as you type, an “Add …” row for new values, and a max that keeps the field to the seats left.
- **Edit and collapse**: Backspace selects the last chip and a second press makes it editable. Out of focus, lines past a number fold into a rolling “+4”.

## Replaces

a tags input library, chip rendering, paste splitting, duplicate checks, validation messages, name lookup for addresses, a suggestions list

## Where it fits

- **Invite teammates**: Add several email addresses at once and see who they are.
- **Labels and tags**: Tag records with existing or new labels.
- **Recipient fields**: To and Cc fields in a composer.
- **Keyword lists**: Search terms, allowed domains or any list of short values.

## Notes

- The input is a combobox with a listbox of suggestions: arrows move the highlight, Enter picks it (the first match is ready while you type), Escape closes the list and Down opens it again.
- Chips are a list. Left arrow or Backspace at the start of the input moves to the last chip; arrows, Home and End move between chips; Backspace or Enter edits one, Delete removes it, Escape returns to the input. Each remove button is named after its chip.
- Adds, duplicates, invalid values, removals and resolved names are announced in a status region outside the field. The error under the field is linked to the input with aria-describedby.
- Every change notes where the chips sit at the keystroke, lets React lay out the new order, then glides each chip from its old place with an additive transform, so a name that resolves while a paste is still landing adds its own glide instead of restarting anything. Leaving and flying copies live in an overlay so the list never waits for them. Nothing runs between changes.
- On touch screens the input uses 16px text so phones don't zoom into it; the chip's letters scale down to 13px as the shell grows.
- Reduced motion adds, removes and resolves in place; colour, icons and the line under the field still say what happened.

License: MIT (https://hairlineui.com/license#components)
