Skip to content

TagInput

Form

Free-form tag creation with case-insensitive deduplication, paste, and explicit limits.

Editable project tagsComma/newline pasteLength and count feedbackDisabled managed labels
Open preview

Responsive viewport — resize the window to explore. Direction and density apply only to this preview. Theme applies to the docs too.

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
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.

TagInput props
PropType / DefaultDescription
labelstring

Default: required

Visible input label.
valuestring[]

Default: required

Controlled unique tag strings.
onValueChange(tags: string[]) => void

Default: required

Apply committed additions/removals.
maxTagsnumber

Default: 8

Nonnegative maximum saved tags.
maxTagLengthnumber

Default: 32

Positive maximum characters per tag.
namestring

Default: —

Emit one hidden form field for each committed tag.
placeholderstring

Default: Add a tag…

Draft input placeholder.
disabledboolean

Default: false

Prevent changes.
classNamestring

Default: —

Extend the container with semantic theme utilities.

Build with these too