Tags input
A comma-separated text field enhanced with removable tags and an explicit add button.
pnpm dlx shadcn@latest add @haze/tags-input---
import { Plus, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";
import Input from "./input.astro";
interface Props {
id: string;
name?: string;
label?: string;
value?: string[];
hint?: string;
addLabel?: string;
removeLabel?: string;
required?: boolean;
form?: string;
class?: string;
[key: string]: unknown;
}
const {
id, name = id, label = "Tags", value = [], hint = "Separate tags with commas.",
addLabel = "Add tag", removeLabel = "Remove", required, form, class: className,
"aria-describedby": additionalDescription, ...rest
} = Astro.props;
const describedBy = [hint ? `${id}-hint` : undefined, additionalDescription].filter(Boolean).join(" ") || undefined;
const initial = value.join(", ");
---
<div data-haze-tags-input data-remove-label={removeLabel} class={cn("grid w-full min-w-0 gap-2", className)}>
<label for={id} class="text-[0.8125rem]/5 font-medium text-foreground">{label}</label>
<ul data-tags-list aria-label={label} class="hidden flex-wrap gap-1.5 [[data-haze-tags-input][data-enhanced]_&:not(:empty)]:flex"></ul>
<div class="flex min-w-0 items-center gap-1.5">
<Input {...rest} id={id} name={name} type="text" value={initial} required={required} form={form}
autocomplete="off" aria-describedby={describedBy} data-tags-editor />
<Button data-tags-add aria-label={addLabel} size="icon" variant="outline" class="hidden [[data-haze-tags-input][data-enhanced]_&]:inline-flex active:scale-90">
<Plus aria-hidden="true" />
</Button>
</div>
{hint && <p id={`${id}-hint`} class="text-[0.8125rem]/5 text-muted-foreground">{hint}</p>}
<input type="hidden" name={name} value={initial} form={form} disabled data-tags-payload />
<p data-tags-status aria-live="polite" class="sr-only"></p>
<template data-tags-template>
<li class="inline-flex max-w-full min-w-0 items-center gap-1 rounded-full border border-frame bg-muted ps-2.5 pe-0.5 py-0.5 text-xs/5 font-medium text-foreground">
<span data-tag class="min-w-0 wrap-anywhere"></span>
<button type="button" data-remove class="grid size-5 shrink-0 cursor-pointer place-items-center rounded-full text-muted-foreground transition-[background-color,color,scale] duration-150 ease-snappy hover:bg-accent hover:text-foreground active:scale-90 active:duration-75 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring disabled:cursor-not-allowed disabled:opacity-50">
<X aria-hidden="true" class="size-3.5" />
</button>
</li>
</template>
</div>
<script>
const parseTags = (text: string) =>
[...new Set(text.split(",").map((tag) => tag.trim()).filter(Boolean))];
function enhance(root: HTMLElement) {
if (root.hasAttribute("data-enhanced")) return;
const editor = root.querySelector<HTMLInputElement>("[data-tags-editor]");
const payload = root.querySelector<HTMLInputElement>("[data-tags-payload]");
const list = root.querySelector<HTMLUListElement>("[data-tags-list]");
const template = root.querySelector<HTMLTemplateElement>("[data-tags-template]");
const add = root.querySelector<HTMLButtonElement>("[data-tags-add]");
const status = root.querySelector<HTMLElement>("[data-tags-status]");
if (!editor || !payload || !list || !template || !add || !status) return;
let tags = parseTags(editor.value);
const required = editor.required;
editor.removeAttribute("name");
editor.value = "";
const sync = () => {
payload.value = parseTags([...tags, editor.value].join(",")).join(", ");
payload.disabled = editor.disabled;
editor.required = required && tags.length === 0;
editor.setCustomValidity(editor.required && editor.value && !payload.value ? "Enter a tag." : "");
add.disabled = editor.disabled || editor.readOnly;
};
let shown: Set<string> | null = null;
const render = () => {
list.replaceChildren();
for (const tag of tags) {
const row = template.content.cloneNode(true) as DocumentFragment;
if (shown && !shown.has(tag)) row.firstElementChild?.classList.add("motion-safe:animate-rise");
row.querySelector("[data-tag]")!.textContent = tag;
const remove = row.querySelector<HTMLButtonElement>("[data-remove]")!;
remove.setAttribute("aria-label", `${root.dataset.removeLabel || "Remove"} ${tag}`);
remove.disabled = editor.disabled || editor.readOnly;
remove.addEventListener("click", () => {
tags = tags.filter((item) => item !== tag);
editor.focus();
render();
sync();
status.textContent = `Removed ${tag}.`;
});
list.append(row);
}
shown = new Set(tags);
};
const commit = () => {
const candidates = parseTags(editor.value);
if (!candidates.length || editor.readOnly || editor.matches(":disabled")) return;
const added = candidates.filter((tag) => !tags.includes(tag));
tags.push(...added);
editor.value = "";
render();
sync();
status.textContent = added.length ? `Added ${added.join(", ")}.` : "Those tags are already added.";
};
editor.addEventListener("input", (event) => {
sync();
if (!(event instanceof InputEvent && event.isComposing) && editor.value.includes(",")) commit();
});
editor.addEventListener("keydown", (event) => {
if (event.key !== "Enter" || event.isComposing || !parseTags(editor.value).length) return;
event.preventDefault();
commit();
});
add.addEventListener("click", () => {
commit();
editor.focus();
});
editor.form?.addEventListener("reset", (event) => queueMicrotask(() => {
if (event.defaultPrevented) return;
tags = parseTags(editor.defaultValue);
editor.value = "";
status.textContent = "";
render();
sync();
}));
new MutationObserver(() => { render(); sync(); }).observe(editor, { attributeFilter: ["disabled", "readonly"] });
render();
sync();
root.setAttribute("data-enhanced", "");
}
const init = () => document.querySelectorAll<HTMLElement>("[data-haze-tags-input]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-tags-input-listener")) {
document.documentElement.setAttribute("data-haze-tags-input-listener", "");
document.addEventListener("astro:page-load", init);
}
</script>When to use
- People attach several short free-form labels to an item
- The set can include values outside a predefined list
When not to use
- The value must come from a predefined list. Use select or checkbox.
- Values may contain commas or need more structure than a label.
Installation
Add the Haze registry to components.json once, then install Tags input with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/tags-inputnpx shadcn@latest add @haze/tags-inputyarn dlx shadcn@latest add @haze/tags-inputbunx --bun shadcn@latest add @haze/tags-inputFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique control ID. Use it to associate a label with the input. |
| name | string | id | Form field name. |
| label | string | "Tags" | Visible field label. |
| value | string[] | [] | Initial tags without commas. |
| hint | string | "Separate tags with commas." | Instructions placed below the field. |
| addLabel | string | "Add tag" | Accessible name of the add button. |
| removeLabel | string | "Remove" | Accessible prefix for a tag removal button. |
| required | boolean | – | Requires at least one tag. |
| form | string | – | ID of the form that owns the field if it is outside the form. |
| ...attributes | HTML input attributes | – | Additional attributes for the native input. |
| class | string | – | Additional classes on the wrapper. |
Keyboard interactions
- Enter or comma
- Add the draft as a tag.
- Tab then Enter or Space
- Focus and activate an add or remove button.
Accessibility
- The submitted value is one comma-separated string. The plain field accepts the same format without JavaScript.
- After a removal, focus returns to the editor and the change is announced.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Tags input" with `npx shadcn@latest add @haze/tags-input`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import TagsInput from "@/components/haze/ui/tags-input.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/tags-input.md
Customize with real content
Adapt the Haze tags-input ui for our product. Replace the demo values of these props with our real content: id, name, label, value, hint, addLabel, removeLabel, required, form, ...attributes, class. Keep the layout, the heading level rules and these accessibility details: The submitted value is one comma-separated string. The plain field accepts the same format without JavaScript. After a removal, focus returns to the editor and the change is announced. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using tags-input, check it fits: use it when people attach several short free-form labels to an item; the set can include values outside a predefined list. Avoid it when the value must come from a predefined list. use select or checkbox.; values may contain commas or need more structure than a label.. Alternatives: @haze/input, @haze/tag, @haze/checkbox.
Dependencies
- npm: @lucide/astro
- @haze/button
- @haze/input
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.