# Tag Input

> A text field that turns what you type into chips that spring into place. Paste a list to add several, and Backspace twice to remove the last.

Category: Inputs · Free · Updated 2026-11-12 · Live demo: https://www.motionkitui.com/components/tag-input

## When to use it

Skills on a profile, labels on a ticket, topics on a post, recipients in an invite form: anywhere people enter a short list of values.

## How it works

Each tag is a list item inside an AnimatePresence with popLayout, so new chips spring in and the rest slide along with layout animation. Enter and comma commit what's typed, a paste containing commas or new lines is split into several tags, and a duplicate pulses the chip that already exists instead of adding another. Backspace in an empty field first selects the last chip, then removes it on a second press, so nothing vanishes by accident.

## Installation

```bash
npx shadcn@latest add https://www.motionkitui.com/r/tag-input.json
```

Or copy `components/motionkit/tag-input.tsx` below. Requires react, motion and Tailwind CSS v4. Free for personal projects; commercial use needs MotionKit Plus (https://www.motionkitui.com/pricing).

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `defaultTags` | `string[]` | `[]` | Tags to start with, when the component manages them. |
| `tags` | `string[]` |  | The tags, if you control them. Pair with onChange. |
| `onChange` | `(tags: string[]) => void` |  | Called with the new list whenever a tag is added or removed. |
| `label` | `string` | `"Tags"` | Visible label above the field. |
| `placeholder` | `string` | `"Add a tag…"` | Placeholder text in the field. |
| `max` | `number` | `12` | The most tags allowed; the field disables itself once it's reached. |
| `accent` | `string` | `"#5FAEB4"` | Colour of the chips and the focus border. |

## Accessibility

- **Keyboard: Pass.** A native text input: Enter or comma adds a tag, Backspace in an empty field selects then removes the last one, and each chip's remove button is reachable with Tab.
- **Screen readers: Pass.** The field has a visible label and a hint, the chips are a labelled list, each remove button names its tag, and additions and removals are announced.
- **Reduced motion: Pass.** With reduced motion on, chips fade in and out without the spring, and the limit-reached shake is skipped.
- **Colour contrast: Pass.** Chip text on the default accent measures 7.5:1, and the hint text 7.1:1 on the field.

## Source

```tsx
"use client";

import { useId, useRef, useState, type ClipboardEvent, type CSSProperties, type KeyboardEvent } from "react";
import { AnimatePresence, motion, useAnimationControls, useReducedMotion } from "motion/react";

type TagInputProps = {
  /** Tags to start with (uncontrolled). */
  defaultTags?: string[];
  /** The tags, if you control them. Pair with onChange. */
  tags?: string[];
  onChange?: (tags: string[]) => void;
  /** Visible label above the field. */
  label?: string;
  placeholder?: string;
  /** The most tags allowed; the field disables itself once it's reached. */
  max?: number;
  /** Colour of the chips and focus ring. */
  accent?: string;
  className?: string;
};

/**
 * A text field that turns what you type into chips. Enter or a comma adds one (pasting "a, b, c" adds three), each
 * chip springs into place, and Backspace in an empty field selects the last chip, then removes it. A duplicate
 * nudges the chip that already exists instead of adding a second.
 */
export function TagInput({
  defaultTags = [],
  tags: controlled,
  onChange,
  label = "Tags",
  placeholder = "Add a tag…",
  max = 12,
  accent = "#5FAEB4",
  className = "",
}: TagInputProps) {
  const reduceMotion = useReducedMotion();
  const id = useId();
  const input = useRef<HTMLInputElement>(null);
  const [own, setOwn] = useState(defaultTags);
  const tags = controlled ?? own;
  const [draft, setDraft] = useState("");
  // Backspace once selects the last chip, twice removes it, so nothing disappears by accident
  const [armed, setArmed] = useState(false);
  const [nudged, setNudged] = useState<string | null>(null);
  const [announcement, setAnnouncement] = useState("");
  const shake = useAnimationControls();
  const full = tags.length >= max;

  function commit(next: string[]) {
    if (controlled === undefined) setOwn(next);
    onChange?.(next);
  }

  function add(raw: string[]) {
    const next = [...tags];
    const added: string[] = [];
    for (const value of raw.map((part) => part.trim()).filter(Boolean)) {
      const existing = next.find((tag) => tag.toLowerCase() === value.toLowerCase());
      if (existing) {
        setNudged(existing);
        window.setTimeout(() => setNudged(null), 450);
        continue;
      }
      if (next.length >= max) {
        if (!reduceMotion) shake.start({ x: [0, -6, 6, -4, 4, 0], transition: { duration: 0.35 } });
        break;
      }
      next.push(value);
      added.push(value);
    }
    if (added.length) {
      commit(next);
      setAnnouncement(`Added ${added.join(", ")}`);
    }
    setDraft("");
  }

  function remove(tag: string) {
    commit(tags.filter((other) => other !== tag));
    setAnnouncement(`Removed ${tag}`);
    setArmed(false);
    input.current?.focus();
  }

  function keyDown(event: KeyboardEvent<HTMLInputElement>) {
    if ((event.key === "Enter" || event.key === ",") && draft.trim()) {
      event.preventDefault();
      add([draft]);
    } else if (event.key === "Backspace" && !draft && tags.length) {
      event.preventDefault();
      if (armed) remove(tags[tags.length - 1]);
      else setArmed(true);
    } else {
      setArmed(false);
    }
  }

  function paste(event: ClipboardEvent<HTMLInputElement>) {
    const text = event.clipboardData.getData("text");
    if (!/[,\n]/.test(text)) return;
    event.preventDefault();
    add(text.split(/[,\n]/));
  }

  const spring = reduceMotion ? { duration: 0 } : { type: "spring" as const, stiffness: 520, damping: 30 };

  return (
    <div className={`w-full max-w-md text-left ${className}`}>
      <label htmlFor={id} className="mb-2 block text-sm font-medium text-[#F6F1E8]">
        {label}
      </label>
      <motion.div
        animate={shake}
        onClick={() => input.current?.focus()}
        className="flex min-h-12 cursor-text flex-wrap items-center gap-1.5 rounded-2xl border border-white/10 bg-[#141B1B] p-2 transition-colors focus-within:border-[var(--tag-accent)]"
        style={{ "--tag-accent": accent } as CSSProperties}
      >
        <ul aria-label={`${label}: ${tags.length} added`} className="contents">
          <AnimatePresence mode="popLayout" initial={false}>
            {tags.map((tag, index) => {
              const selected = armed && index === tags.length - 1;
              return (
                <motion.li
                  key={tag}
                  layout={!reduceMotion}
                  initial={reduceMotion ? { opacity: 0 } : { opacity: 0, scale: 0.6, y: 4 }}
                  animate={nudged === tag && !reduceMotion ? { opacity: 1, scale: [1, 1.12, 1], y: 0 } : { opacity: 1, scale: 1, y: 0 }}
                  exit={reduceMotion ? { opacity: 0 } : { opacity: 0, scale: 0.6, transition: { duration: 0.15 } }}
                  transition={spring}
                  className="flex items-center gap-1 rounded-full py-1 pl-3 pr-1 text-sm text-[#0C1010]"
                  style={{ background: accent, boxShadow: selected ? `0 0 0 2px #0C1010, 0 0 0 4px ${accent}` : undefined }}
                >
                  {tag}
                  <button
                    type="button"
                    onClick={(event) => {
                      event.stopPropagation();
                      remove(tag);
                    }}
                    aria-label={`Remove ${tag}`}
                    className="grid size-5 place-items-center rounded-full transition hover:bg-black/15 focus-visible:outline-2 focus-visible:outline-[#0C1010]"
                  >
                    <svg aria-hidden viewBox="0 0 12 12" className="size-2.5">
                      <path d="M2 2l8 8M10 2l-8 8" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
                    </svg>
                  </button>
                </motion.li>
              );
            })}
          </AnimatePresence>
        </ul>
        <input
          ref={input}
          id={id}
          value={draft}
          disabled={full}
          onChange={(event) => {
            setDraft(event.target.value.replace(",", ""));
            setArmed(false);
          }}
          onKeyDown={keyDown}
          onPaste={paste}
          onBlur={() => {
            setArmed(false);
            if (draft.trim()) add([draft]);
          }}
          placeholder={full ? `Up to ${max} tags` : placeholder}
          aria-describedby={`${id}-hint`}
          className="min-w-24 flex-1 bg-transparent px-1.5 py-1 text-sm text-[#F6F1E8] outline-none placeholder:text-[#94A9A7] disabled:cursor-not-allowed"
        />
      </motion.div>
      <p id={`${id}-hint`} className="mt-1.5 text-xs text-[#94A9A7]">
        Press Enter or comma to add. Backspace twice removes the last tag.
      </p>
      <p aria-live="polite" className="sr-only">
        {announcement}
      </p>
    </div>
  );
}
```
