TagInput
FormFree-form tag creation with case-insensitive deduplication, paste, and explicit limits.
Responsive viewport — resize the window to explore. Direction and density apply only to this preview. Theme applies to the docs too.
"use client";
import { TagInput } from "@/components/ui/tag-input";
import { useState } from "react";
export default function TagInputExample() {
const [tags, setTags] = useState(["design", "accessibility"]);
return (
<div className="w-full max-w-lg space-y-7">
<div>
<h3 className="font-semibold">Keep your work discoverable</h3>
<p className="mt-1 text-sm text-muted-foreground">
Create a small, useful vocabulary for your team.
</p>
</div>
<TagInput
label="Project tags"
value={tags}
onValueChange={setTags}
maxTags={5}
maxTagLength={18}
name="tags"
/>
<p role="status" className="text-xs text-muted-foreground">
{tags.length ? tags.join(" · ") : "No tags yet."}
</p>
<TagInput
label="Managed labels"
value={["internal", "confidential"]}
onValueChange={() => {}}
disabled
/>
</div>
);
}Usage
Own a unique array of tags. Enter or comma commits the current draft; a pasted comma/newline list is handled atomically. Whitespace is trimmed, case-insensitive duplicates are ignored, and overlong or over-limit batches are rejected without partially modifying the value. Draft text remains until committed or cleared with Escape. Each tag can be removed explicitly; empty Backspace never silently deletes a saved tag. name creates repeated hidden form fields.
import { TagInput } from "@/components/ui/tag-input";Shipped as editable source in src/components/ui/tag-input.tsx in both apps. Copy the implementation below when moving it to another project. Copy the complete example from Source code for all imports and state. Add "use client" when using hooks or event handlers. See installation and theming for project setup.
Component source
The complete implementation is included in both apps. It uses the React, Radix, Lucide, and shared-core dependencies already installed in Apex. Keep your project’s semantic theme tokens when reusing it.
src/components/ui/tag-input.tsx
"use client";
import { useId, useRef, useState } from "react";
import { X } from "lucide-react";
import { Label } from "@dashboardpack/core/components/ui/label";
import { cn } from "@dashboardpack/core/lib/utils";
export function normalizeTags(values: string[], maxLength = 32) {
const seen = new Set<string>();
return values
.map((value) => value.trim())
.filter((value) => {
const key = value.toLocaleLowerCase();
if (!value || value.length > maxLength || seen.has(key)) return false;
seen.add(key);
return true;
});
}
export interface TagInputProps {
label: string;
value: string[];
onValueChange: (value: string[]) => void;
maxTags?: number;
maxTagLength?: number;
disabled?: boolean;
name?: string;
placeholder?: string;
className?: string;
}
export function TagInput({
label,
value,
onValueChange,
maxTags = 8,
maxTagLength = 32,
disabled,
name,
placeholder = "Add a tag…",
className,
}: TagInputProps) {
const id = useId();
const input = useRef<HTMLInputElement>(null);
const [draft, setDraft] = useState("");
const [error, setError] = useState("");
const limit = Math.max(0, Number.isFinite(maxTags) ? Math.floor(maxTags) : 8);
const length = Math.max(
1,
Number.isFinite(maxTagLength) ? Math.floor(maxTagLength) : 32,
);
const add = (values: string[]) => {
const supplied = values.map((item) => item.trim()).filter(Boolean);
if (supplied.some((item) => item.length > length)) {
setError(`Keep each tag to ${length} characters.`);
return;
}
const next = normalizeTags([...value, ...supplied], length);
if (next.length > limit) {
setError(`Use up to ${limit} tags.`);
return;
}
onValueChange(next);
setDraft("");
setError("");
};
return (
<div className={cn("min-w-0 space-y-2", className)}>
<Label htmlFor={id}>{label}</Label>
<div
className={cn(
"flex min-h-11 flex-wrap items-center gap-2 rounded-xl border border-input bg-background p-2 focus-within:ring-2 focus-within:ring-ring",
disabled && "bg-muted/30",
)}
>
{value.map((tag) => (
<span
key={tag}
className="inline-flex max-w-full items-center gap-1 rounded-md bg-secondary px-2 py-1 text-xs text-secondary-foreground"
>
<span className="break-all">{tag}</span>
<button
type="button"
aria-label={`Remove tag ${tag}`}
disabled={disabled}
onClick={() => {
onValueChange(value.filter((item) => item !== tag));
setError("");
input.current?.focus();
}}
className="rounded outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<X className="size-3" />
</button>
{name && <input type="hidden" name={name} value={tag} />}
</span>
))}
<input
ref={input}
id={id}
value={draft}
disabled={disabled}
className="min-w-0 flex-1 basis-28 bg-transparent px-1 py-1 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed"
placeholder={placeholder}
aria-describedby={`${id}-help${error ? ` ${id}-error` : ""}`}
onChange={(event) => setDraft(event.target.value)}
onKeyDown={(event) => {
if (event.nativeEvent.isComposing) return;
if (event.key === "Enter" || event.key === ",") {
event.preventDefault();
add([draft]);
}
if (event.key === "Escape") {
setDraft("");
setError("");
}
}}
onPaste={(event) => {
const text = event.clipboardData.getData("text");
if (/[,\n]/.test(text)) {
event.preventDefault();
add(text.split(/[,\r\n]+/));
}
}}
/>
</div>
<p id={`${id}-help`} className="text-xs text-muted-foreground">
Enter or comma adds a tag. Paste a comma-separated list. {value.length}{" "}
/ {limit} tags.
</p>
{error && (
<p id={`${id}-error`} role="alert" className="text-xs text-destructive">
{error}
</p>
)}
</div>
);
}API reference
Common props and defaults. Slot-specific props are named below; native elements also accept their standard HTML attributes. The component TypeScript definitions are the complete type reference.
| Prop | Type / Default | Description |
|---|---|---|
| label | stringDefault: required | Visible input label. |
| value | string[]Default: required | Controlled unique tag strings. |
| onValueChange | (tags: string[]) => voidDefault: required | Apply committed additions/removals. |
| maxTags | numberDefault: 8 | Nonnegative maximum saved tags. |
| maxTagLength | numberDefault: 32 | Positive maximum characters per tag. |
| name | stringDefault: — | Emit one hidden form field for each committed tag. |
| placeholder | stringDefault: Add a tag… | Draft input placeholder. |
| disabled | booleanDefault: false | Prevent changes. |
| className | stringDefault: — | Extend the container with semantic theme utilities. |