Skip to content
Molecules

Tag input

Enter or comma adds a tag, Backspace removes.

Variants

2 more takes on the tag input, each a single file you install on its own by its id.

aui-048Email chips

Pasted addresses split into chips.

$ pnpm dlx asta-ui@latest add tag-input-aui-048

Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/tag-input-aui-048.json

aui-049Suggested tags

Tab accepts a ghost completion.

$ pnpm dlx asta-ui@latest add tag-input-aui-049

Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/tag-input-aui-049.json

Installation

  1. Run the CLI

    Run pnpm dlx asta-ui@latest init once, then this. The file lands in components/astabyte/ and the colour tokens go into your CSS.

    $ pnpm dlx asta-ui@latest add tag-input

    Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/tag-input.json

  2. Or install the package

    Don’t want the file? Import from asta-ui/tag-input and update with pnpm update asta-ui. Add the stylesheet once. More.

    $ pnpm add asta-ui
    import { TagInput } from "asta-ui/tag-input";
  3. Or copy it by hand

    Copy this file. Keep the paths, or fix the @/ imports. Then add the tokens from globals.css.

    "use client";
    
    import { useId, useRef, useState } from "react";
    
    const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
    
    export interface TagInputProps {
      value?: string[];
      defaultValue?: string[];
      onChange?: (tags: string[]) => void;
      /** Most tags allowed. */
      max?: number;
      placeholder?: string;
      label?: string;
      /** Form field name. Each tag is sent as its own hidden input with this name. */
      name?: string;
      className?: string;
    }
    
    /**
     * Type and press Enter or comma to add a tag. Backspace on an empty field marks the last tag, a second
     * Backspace removes it. Pasting "a, b, c" adds all three. A duplicate makes the existing tag shake.
     */
    export function TagInput({ value, defaultValue = [], onChange, max = 8, placeholder = "Add a tag…", label = "Tags", name, className }: TagInputProps) {
      const [inner, setInner] = useState(defaultValue);
      const tags = value ?? inner;
      const [text, setText] = useState("");
      const [armed, setArmed] = useState(false);
      const [shake, setShake] = useState<{ tag: string; n: number } | null>(null);
      const input = useRef<HTMLInputElement>(null);
      const id = useId();
      const full = tags.length >= max;
    
      const set = (next: string[]) => {
        if (value === undefined) setInner(next);
        onChange?.(next);
      };
    
      const add = (raw: string[]) => {
        const next = [...tags];
        for (const r of raw) {
          const t = r.trim().replace(/\s+/g, " ");
          if (!t) continue;
          const dup = next.find((x) => x.toLowerCase() === t.toLowerCase());
          if (dup) {
            setShake((s) => ({ tag: dup, n: (s?.n ?? 0) + 1 }));
            continue;
          }
          if (next.length >= max) break;
          next.push(t);
        }
        if (next.length !== tags.length) set(next);
        setText("");
      };
    
      const remove = (t: string) => {
        set(tags.filter((x) => x !== t));
        setArmed(false);
        input.current?.focus();
      };
    
      return (
        <div className={cx("w-full", className)}>
          <div className="mb-2 flex items-baseline justify-between">
            <label htmlFor={id} className="text-[13px] font-medium text-ink">
              {label}
            </label>
            <span className={cx("font-mono text-[11px] tabular-nums transition-colors", full ? "text-ink" : "text-mute")} aria-live="polite">
              {tags.length}/{max}
            </span>
          </div>
          <div
            onClick={() => input.current?.focus()}
            className={cx(
              "flex min-h-11 w-full cursor-text flex-wrap items-center gap-1.5 rounded-[9px] bg-paper p-1.5 transition-shadow duration-200",
              "shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_14%,transparent)]",
              "focus-within:shadow-[inset_0_0_0_1px_var(--color-brand),0_0_0_4px_color-mix(in_srgb,var(--color-brand)_14%,transparent)]",
            )}
          >
            <style href="asta-tag-input" precedence="asta">{`
              @keyframes kit-tag-in { from { transform: scale(.6); opacity: 0 } }
              @keyframes kit-tag-shake { 0%,100% { transform: none } 20% { transform: translateX(-4px) } 40% { transform: translateX(4px) } 60% { transform: translateX(-3px) } 80% { transform: translateX(2px) } }
              @media (prefers-reduced-motion: reduce) { [data-kit-tag] { animation: none !important } }
            `}</style>
            <ul className="contents" aria-label={label}>
              {tags.map((t, i) => {
                const last = i === tags.length - 1;
                const shaking = shake?.tag === t;
                return (
                  <li
                    key={shaking ? `${t}-${shake.n}` : t}
                    data-kit-tag
                    className={cx(
                      "flex h-8 items-center gap-1 rounded-md pl-3 pr-1 text-[13px] transition-colors duration-200",
                      last && armed ? "bg-ink text-paper" : "bg-paper-2 text-ink",
                    )}
                    style={{ animation: shaking ? "kit-tag-shake .4s ease" : "kit-tag-in .35s cubic-bezier(.16,1,.3,1)" }}
                  >
                    {t}
                    <button
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        remove(t);
                      }}
                      aria-label={`Remove ${t}`}
                      className={cx(
                        "flex h-6 w-6 items-center justify-center rounded-[5px] outline-none transition-colors focus-visible:ring-2 focus-visible:ring-brand/50",
                        last && armed ? "hover:bg-paper/20" : "text-mute hover:bg-[color-mix(in_srgb,var(--color-ink)_8%,transparent)] hover:text-ink",
                      )}
                    >
                      <svg viewBox="0 0 24 24" className="h-3 w-3" fill="none" stroke="currentColor" strokeWidth="2.7" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
                        <path d="m6 6 12 12" />
                        <path d="M18 6 6 18" />
                      </svg>
                    </button>
                  </li>
                );
              })}
            </ul>
            <input
              ref={input}
              id={id}
              autoComplete="off"
              enterKeyHint="enter"
              value={text}
              disabled={full && !text}
              placeholder={full ? "Limit reached" : tags.length ? "" : placeholder}
              onChange={(e) => {
                setArmed(false);
                const v = e.target.value;
                if (v.includes(",")) add(v.split(","));
                else setText(v);
              }}
              onPaste={(e) => {
                const v = e.clipboardData.getData("text");
                if (/[,\n]/.test(v)) {
                  e.preventDefault();
                  add(v.split(/[,\n]/));
                }
              }}
              onKeyDown={(e) => {
                if (e.key === "Enter") {
                  e.preventDefault();
                  add([text]);
                } else if (e.key === "Backspace" && !text && tags.length) {
                  if (armed) remove(tags[tags.length - 1]);
                  else setArmed(true);
                } else if (e.key === "Escape") setArmed(false);
              }}
              onBlur={() => {
                setArmed(false);
                if (text.trim()) add([text]);
              }}
              className="h-8 min-w-[4rem] flex-1 bg-transparent px-2 text-[16px] sm:text-[14px] text-ink outline-none placeholder:text-mute disabled:cursor-not-allowed"
            />
          </div>
          {name && tags.map((t) => <input key={t} type="hidden" name={name} value={t} />)}
          <p className="mt-2 text-[12px] text-mute">
            <kbd className="font-sans text-ink-2">Enter</kbd> or <kbd className="font-sans text-ink-2">,</kbd> to add ·{" "}
            <kbd className="font-sans text-ink-2">⌫</kbd> twice to remove
          </p>
        </div>
      );
    }
    
    export default TagInput;
    
  4. Or ask your AI agent

    Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.

    Add the Astabyte UI Tag input component to my project.
    
    Enter or comma adds a tag, Backspace removes.
    It includes: add, remove, paste, limit.
    
    Install it:
    ```sh
    pnpm dlx asta-ui@latest add tag-input --radix
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/tag-input.json
    ```
    If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4).
    
    Import it like this:
    ```tsx
    import { TagInput } from "@/components/astabyte/tag-input";
    ```
    
    Usage example and props: https://ui.astabyte.com/tag-input
    Full catalogue for context: https://ui.astabyte.com/llms.txt
    
    Rules:
    - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS.
    - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback.
    - Keep keyboard, focus and ARIA behaviour.
    - Use fake data and fake brand names in examples.
    
    Use it to: [describe where it goes and what it should do]
  5. Or use plain HTML + CSS

    Not on React? Use it from Django, Rails, Laravel, Go html/template, htmx or a static page. Load asta.css and asta.js once (the head.html tab), then paste the markup. The ui.astabyte.com/cdn link is temporary: pin a version from jsDelivr for production. More in HTML + CSS.

    <!-- Needs asta.js to add and remove tags. -->
    <form style="display:flex;flex-direction:column;align-items:flex-start;gap:16px"><div data-asta-tags data-name="tag" data-max="6" data-placeholder="Add a tag" class="asta-tag-input"><div class="asta-tag-input-head"><label for="tags" class="asta-tag-input-label">Tags</label> <span data-asta-tags-count aria-live="polite" class="asta-tag-input-count">2/6</span></div><div data-asta-tags-box class="asta-tag-input-box"><ul class="asta-tag-input-list" aria-label="Tags" data-asta-tags-list><li data-asta-tag="design" class="asta-tag-input-tag"><span data-asta-tag-text>design</span> <button type="button" aria-label="Remove design" data-asta-tag-remove class="asta-tag-input-remove"><svg viewBox="0 0 16 16"  fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="m4.5 4.5 7 7M11.5 4.5l-7 7"></path></svg></button> <input type="hidden" name="tag" value="design"></li><li data-asta-tag="go" class="asta-tag-input-tag"><span data-asta-tag-text>go</span> <button type="button" aria-label="Remove go" data-asta-tag-remove class="asta-tag-input-remove"><svg viewBox="0 0 16 16"  fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="m4.5 4.5 7 7M11.5 4.5l-7 7"></path></svg></button> <input type="hidden" name="tag" value="go"></li></ul><input id="tags" data-asta-tags-input autocomplete="off" placeholder="" class="asta-tag-input-field"></div><p class="asta-tag-input-hint"><kbd >Enter</kbd> or <kbd >,</kbd> to add · <kbd >⌫</kbd> twice to remove</p><template data-asta-tags-tpl><li data-asta-tag="" class="asta-tag-input-tag asta-tag-in"><span data-asta-tag-text></span> <button type="button" aria-label="Remove " data-asta-tag-remove class="asta-tag-input-remove"><svg viewBox="0 0 16 16"  fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="m4.5 4.5 7 7M11.5 4.5l-7 7"></path></svg></button> <input type="hidden" name="tag" value=""></li></template></div></form>

Usage

The demo above, as code.

"use client";

import { useState } from "react";
import { TagInput } from "@/components/astabyte/tag-input";

const IDEAS = ["Motion", "Tailwind", "Accessibility", "Design systems"];

export default function TagInputDemo() {
  const [tags, setTags] = useState(["React", "Next.js", "TypeScript"]);

  return (
    <div className="relative flex min-h-[420px] w-full flex-col items-center justify-center gap-5 p-6 sm:p-10">
      <TagInput label="Skills" name="skills" value={tags} onChange={setTags} max={6} placeholder="Add a skill…" className="max-w-md" />
      <div className="flex max-w-md flex-wrap items-center justify-center gap-1.5">
        <span className="text-[12px] text-mute">Try:</span>
        {IDEAS.map((t) => (
          <button
            key={t}
            type="button"
            disabled={tags.length >= 6}
            onClick={() => !tags.some((x) => x.toLowerCase() === t.toLowerCase()) && setTags([...tags, t])}
            className="h-7 rounded-md px-2.5 text-[12px] text-ink-2 shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_14%,transparent)] transition-colors hover:bg-paper-2 hover:text-ink disabled:opacity-40"
          >
            + {t}
          </button>
        ))}
      </div>
    </div>
  );
}