Overview

Type a word and press Enter, comma or Tab to turn it into a chip. Chips pop in out of a light blur and the rest slide aside as they come and go. Typing a duplicate flashes the chip that already exists instead of ignoring you. suggestions adds an autocomplete list you can move through with the arrow keys, and validate rejects a chip with a message and a small shake. Backspace on an empty field highlights the last chip, and a second press removes it; Left and Right move that highlight. Pasting a comma-separated list adds every item at once, and a counter shows how close you are to max.


Installation

Use the CLI to install the component automatically:

$ pnpm dlx shadcn@latest add https://ui.sanjid.in/r/chip-input.json

Install dependencies:

$ pnpm add motion lucide-react

Add the utility function for class merging:

lib/utils.ts
tsx
import { ClassValue, clsx } from "clsx";import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {  return twMerge(clsx(inputs));}

Copy the component code into your project:

components/ui/chip-input.tsx
tsx
"use client";
import React, { useCallback, useId, useRef, useState } from "react";import {  AnimatePresence,  motion,  useAnimate,  useReducedMotion,} from "motion/react";import { X } from "lucide-react";import { cn } from "@/lib/utils";
export type ChipInputProps = {  value?: string[];  defaultValue?: string[];  onChange?: (value: string[]) => void;  placeholder?: string;  /** Accessible name for the field. Defaults to the placeholder. */  label?: string;  max?: number;  /** Autocomplete options, filtered as you type. */  suggestions?: string[];  /** Return a message to reject a chip, or nothing to accept it. */  validate?: (chip: string) => string | null | undefined | void;  disabled?: boolean;  className?: string;};
const SPRING = { type: "spring" as const, bounce: 0.2, duration: 0.4 };
function splitTokens(raw: string): string[] {  return raw    .split(/[,|\n]+/)    .map((s) => s.trim())    .filter(Boolean);}
export function ChipInput({  value: valueProp,  defaultValue = [],  onChange,  placeholder = "Add tag…",  label,  max,  suggestions = [],  validate,  disabled,  className,}: ChipInputProps) {  const reduce = !!useReducedMotion();  const uid = useId();  const isControlled = valueProp !== undefined;  const [uncontrolled, setUncontrolled] = useState(defaultValue);  const chips = isControlled ? valueProp : uncontrolled;  const [draft, setDraft] = useState("");  const [highlight, setHighlight] = useState<number | null>(null);  const [flash, setFlash] = useState<{ chip: string; token: number } | null>(    null,  );  const [error, setError] = useState<string | null>(null);  const [focused, setFocused] = useState(false);  const [activeSuggestion, setActiveSuggestion] = useState(0);  const [navigated, setNavigated] = useState(false);  const [announcement, setAnnouncement] = useState("");  const inputRef = useRef<HTMLInputElement>(null);  const [scope, animate] = useAnimate<HTMLDivElement>();
  const full = max != null && chips.length >= max;  const lower = new Set(chips.map((c) => c.toLowerCase()));  const query = draft.trim().toLowerCase();  const matches = suggestions    .filter(      (s) =>        !lower.has(s.toLowerCase()) &&        (!query || s.toLowerCase().includes(query)),    )    .slice(0, 6);  const listOpen = focused && !full && !disabled && matches.length > 0;  const showActive = query.length > 0 || navigated;  const listId = `${uid}-list`;
  const setChips = useCallback(    (next: string[]) => {      if (!isControlled) setUncontrolled(next);      onChange?.(next);    },    [isControlled, onChange],  );
  const reject = (message: string) => {    setError(message);    if (!reduce && scope.current) {      animate(        scope.current,        { x: [0, -6, 5, -3, 2, 0] },        { duration: 0.36, ease: "easeOut" },      );    }  };
  const addTokens = (tokens: string[]) => {    if (disabled || tokens.length === 0) return;    const seen = new Set(lower);    const next = [...chips];    for (const t of tokens) {      if (max != null && next.length >= max) {        reject(`Up to ${max} allowed`);        break;      }      const key = t.toLowerCase();      if (seen.has(key)) {        // Point at the chip that already exists instead of silently ignoring.        const existing = next.find((c) => c.toLowerCase() === key) ?? t;        setFlash({ chip: existing, token: Date.now() });        continue;      }      const message = validate?.(t);      if (message) {        reject(message);        continue;      }      seen.add(key);      next.push(t);    }    if (next.length !== chips.length) {      setChips(next);      setError(null);      const added = next.slice(chips.length);      setAnnouncement(`Added ${added.join(", ")}. ${next.length} total.`);    }    setDraft("");    setHighlight(null);    setActiveSuggestion(0);    setNavigated(false);  };
  const removeAt = (index: number) => {    if (disabled) return;    const chip = chips[index];    if (chip === undefined) return;    setChips(chips.filter((_, i) => i !== index));    setError(null);    setHighlight(null);    setAnnouncement(`Removed ${chip}.`);  };
  const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {    const caretAtStart =      e.currentTarget.selectionStart === 0 &&      e.currentTarget.selectionEnd === 0;
    if (listOpen && (e.key === "ArrowDown" || e.key === "ArrowUp")) {      e.preventDefault();      const d = e.key === "ArrowDown" ? 1 : -1;      setActiveSuggestion((i) =>        navigated || query          ? (i + d + matches.length) % matches.length          : d > 0            ? 0            : matches.length - 1,      );      setNavigated(true);      return;    }    if (      e.key === "Enter" ||      e.key === "," ||      (e.key === "Tab" && draft.trim())    ) {      const pick =        listOpen && showActive ? matches[activeSuggestion] : undefined;      if (!pick && !draft.trim()) return;      e.preventDefault();      addTokens(pick ? [pick] : splitTokens(draft));      return;    }    if (e.key === "Escape") {      if (highlight !== null) setHighlight(null);      else if (draft) setDraft("");      return;    }    if (!caretAtStart || !chips.length) return;
    // Backspace highlights the last chip first, a second press removes it.    if (e.key === "Backspace" || e.key === "Delete") {      e.preventDefault();      if (highlight !== null) removeAt(highlight);      else if (e.key === "Backspace") setHighlight(chips.length - 1);    } else if (e.key === "ArrowLeft") {      e.preventDefault();      setHighlight((h) => (h === null ? chips.length - 1 : Math.max(0, h - 1)));    } else if (e.key === "ArrowRight" && highlight !== null) {      e.preventDefault();      setHighlight((h) => (h === null || h >= chips.length - 1 ? null : h + 1));    }  };
  return (    <div className={cn("w-full", className)}>      <div className="relative">        <div          ref={scope}          onClick={() => inputRef.current?.focus()}          className={cn(            "flex min-h-11 w-full cursor-text flex-wrap items-center gap-1.5 rounded-[14px] py-1.5 pr-2 pl-1.5",            "bg-(--color-paper) transition-shadow duration-200",            error              ? "shadow-[inset_0_0_0_1.5px_rgb(239_68_68/0.7)]"              : focused                ? "shadow-[inset_0_0_0_1.5px_var(--color-ink),0_0_0_4px_color-mix(in_oklab,var(--color-ink)_8%,transparent)]"                : "shadow-[inset_0_0_0_1px_var(--color-rule)]",            disabled && "cursor-not-allowed opacity-50",          )}        >          <AnimatePresence initial={false} mode="popLayout">            {chips.map((chip, i) => {              const isHighlighted = highlight === i;              const isFlashing = flash?.chip === chip;              return (                <motion.span                  key={chip}                  layout={reduce ? false : "position"}                  initial={                    reduce                      ? { opacity: 0 }                      : { opacity: 0, scale: 0.6, filter: "blur(4px)" }                  }                  animate={                    isFlashing && !reduce                      ? { opacity: 1, scale: [1, 1.1, 1], filter: "blur(0px)" }                      : { opacity: 1, scale: 1, filter: "blur(0px)" }                  }                  exit={                    reduce                      ? { opacity: 0 }                      : { opacity: 0, scale: 0.6, filter: "blur(4px)" }                  }                  transition={isFlashing ? { duration: 0.4 } : SPRING}                  onAnimationComplete={() => isFlashing && setFlash(null)}                  className={cn(                    "inline-flex h-8 max-w-full items-center gap-0.5 rounded-full pr-1 pl-3 text-[13px] font-medium",                    "transition-[background-color,color,box-shadow] duration-200",                    isHighlighted                      ? "bg-(--color-ink) text-(--color-paper)"                      : isFlashing                        ? "bg-amber-500/15 text-(--color-ink) shadow-[inset_0_0_0_1px_rgb(245_158_11/0.5)]"                        : "bg-(--color-paper-2) text-(--color-ink) shadow-[inset_0_0_0_1px_var(--color-rule)]",                  )}                >                  <span className="truncate">{chip}</span>                  {!disabled ? (                    <button                      type="button"                      tabIndex={-1}                      aria-label={`Remove ${chip}`}                      onClick={(e) => {                        e.stopPropagation();                        removeAt(i);                        inputRef.current?.focus();                      }}                      className={cn(                        "flex size-6 shrink-0 items-center justify-center rounded-full transition-[background-color,transform] duration-150 outline-none active:scale-90",                        isHighlighted                          ? "hover:bg-(--color-paper)/20"                          : "text-(--color-neutral) hover:bg-(--color-ink)/10 hover:text-(--color-ink)",                      )}                    >                      <X className="size-3.5" strokeWidth={2} aria-hidden />                    </button>                  ) : null}                </motion.span>              );            })}          </AnimatePresence>
          <motion.input            layout={reduce ? false : "position"}            transition={SPRING}            ref={inputRef}            role="combobox"            aria-label={label ?? placeholder}            aria-expanded={listOpen}            aria-controls={listOpen ? listId : undefined}            aria-activedescendant={              listOpen && showActive                ? `${listId}-${activeSuggestion}`                : undefined            }            aria-autocomplete="list"            aria-invalid={!!error}            aria-describedby={`${uid}-help`}            value={draft}            disabled={disabled}            readOnly={full}            placeholder={              full ? "" : chips.length === 0 ? placeholder : "Add more…"            }            onChange={(e) => {              setDraft(e.target.value);              setHighlight(null);              setError(null);              setActiveSuggestion(0);              setNavigated(false);            }}            onKeyDown={onKeyDown}            onPaste={(e) => {              const text = e.clipboardData.getData("text");              if (/[,\n|]/.test(text)) {                e.preventDefault();                addTokens(splitTokens(text));              }            }}            onFocus={() => setFocused(true)}            onBlur={() => {              setFocused(false);              setHighlight(null);              if (draft.trim()) addTokens(splitTokens(draft));            }}            className="h-8 min-w-[6rem] flex-1 bg-transparent px-1.5 text-[14px] text-(--color-ink) outline-none placeholder:text-(--color-neutral)"          />        </div>
        <AnimatePresence>          {listOpen ? (            <motion.div              id={listId}              role="listbox"              aria-label="Suggestions"              initial={                reduce                  ? { opacity: 0 }                  : { opacity: 0, y: -4, scale: 0.98, filter: "blur(4px)" }              }              animate={{ opacity: 1, y: 0, scale: 1, filter: "blur(0px)" }}              exit={                reduce                  ? { opacity: 0 }                  : { opacity: 0, y: -4, scale: 0.98, filter: "blur(4px)" }              }              transition={{ duration: 0.18, ease: [0.23, 1, 0.32, 1] }}              className={cn(                "absolute inset-x-0 top-full z-20 mt-1.5 origin-top overflow-hidden rounded-[14px] p-1",                "bg-(--color-paper)/95 shadow-[inset_0_0_0_1px_var(--color-rule),0_12px_32px_-10px_rgba(0,0,0,0.25)] backdrop-blur-xl",              )}            >              {matches.map((s, i) => {                const active = showActive && i === activeSuggestion;                return (                  <div                    key={s}                    id={`${listId}-${i}`}                    role="option"                    aria-selected={active}                    onPointerDown={(e) => {                      e.preventDefault();                      addTokens([s]);                    }}                    onPointerEnter={() => {                      setActiveSuggestion(i);                      setNavigated(true);                    }}                    className={cn(                      "relative flex h-8 cursor-pointer items-center rounded-[10px] px-2.5 text-[13.5px] text-(--color-ink-2)",                      active && "text-(--color-ink)",                    )}                  >                    {active ? (                      <motion.span                        layoutId={`${uid}-suggestion`}                        transition={{                          type: "spring",                          bounce: 0,                          duration: 0.25,                        }}                        className="absolute inset-0 rounded-[10px] bg-(--color-paper-2)"                      />                    ) : null}                    <span className="relative">{s}</span>                  </div>                );              })}            </motion.div>          ) : null}        </AnimatePresence>      </div>
      <div        id={`${uid}-help`}        className="mt-1.5 flex min-h-4 items-center justify-between gap-3 px-1 text-[12px]"      >        <AnimatePresence initial={false} mode="popLayout">          {error ? (            <motion.span              key="error"              initial={{ opacity: 0, y: -4 }}              animate={{ opacity: 1, y: 0 }}              exit={{ opacity: 0, y: -4 }}              className="text-red-600 dark:text-red-400"            >              {error}            </motion.span>          ) : (            <motion.span              key="hint"              initial={{ opacity: 0 }}              animate={{ opacity: 1 }}              exit={{ opacity: 0 }}              className="text-(--color-neutral)"            >              {full ? "Limit reached" : "Enter or comma to add"}            </motion.span>          )}        </AnimatePresence>        {max != null ? (          <span            className={cn(              "tabular-nums transition-colors",              full ? "text-(--color-ink)" : "text-(--color-neutral)",            )}          >            {chips.length}/{max}          </span>        ) : null}      </div>
      <div role="status" aria-live="polite" className="sr-only">        {announcement}      </div>    </div>  );}

Adjust import paths according to your folder structure.


Basic Usage

tsx
import { ChipInput } from "@/components/ui/chip-input";
const [tags, setTags] = useState(["billing"]);
<ChipInput  value={tags}  onChange={setTags}  label="Ticket labels"  max={6}  suggestions={["billing", "bug", "design", "infra", "mobile"]}  validate={(t) => (/\s/.test(t) ? "Use single words" : null)}/>

Props

PropTypeRequiredDefaultDescription
value / defaultValuestring[]No—Controlled or initial chips.
onChange(value: string[]) => voidNo—Fires with the new list after every add or remove.
suggestionsstring[]No—Autocomplete options. Ones already added are hidden; the rest filter as you type.
validate(chip: string) => string | null | voidNo—Return a message to reject a chip. It shows under the field until the next edit.
maxnumberNo—Most chips allowed. Shows a counter and blocks further adds once reached.
placeholder / labelstringNo"Add tag…"Placeholder text, and the field's accessible name (defaults to the placeholder).
disabled / classNameboolean / stringNo—Disable the field, or add classes to the wrapper.

Best Practices

  1. Matching is case-insensitive, so "Billing" and "billing" count as the same chip.
  2. Use validate for format rules and suggestions to steer people toward existing labels.
  3. Leave room below the field for the suggestion list, or place it where the list can overlap content.
  4. Adds and removes are announced to screen readers.