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.jsonInstall dependencies:
$ pnpm add motion lucide-reactAdd the utility function for class merging:
lib/utils.ts
tsx
1import { ClassValue, clsx } from "clsx";2import { twMerge } from "tailwind-merge";3 4export function cn(...inputs: ClassValue[]) {5 return twMerge(clsx(inputs));6}
Copy the component code into your project:
tsx
1"use client";2 3import React, { useCallback, useId, useRef, useState } from "react";4import {5 AnimatePresence,6 motion,7 useAnimate,8 useReducedMotion,9} from "motion/react";10import { X } from "lucide-react";11import { cn } from "@/lib/utils";12 13export type ChipInputProps = {14 value?: string[];15 defaultValue?: string[];16 onChange?: (value: string[]) => void;17 placeholder?: string;18 /** Accessible name for the field. Defaults to the placeholder. */19 label?: string;20 max?: number;21 /** Autocomplete options, filtered as you type. */22 suggestions?: string[];23 /** Return a message to reject a chip, or nothing to accept it. */24 validate?: (chip: string) => string | null | undefined | void;25 disabled?: boolean;26 className?: string;27};28 29const SPRING = { type: "spring" as const, bounce: 0.2, duration: 0.4 };30 31function splitTokens(raw: string): string[] {32 return raw33 .split(/[,|\n]+/)34 .map((s) => s.trim())35 .filter(Boolean);36}37 38export function ChipInput({39 value: valueProp,40 defaultValue = [],41 onChange,42 placeholder = "Add tag…",43 label,44 max,45 suggestions = [],46 validate,47 disabled,48 className,49}: ChipInputProps) {50 const reduce = !!useReducedMotion();51 const uid = useId();52 const isControlled = valueProp !== undefined;53 const [uncontrolled, setUncontrolled] = useState(defaultValue);54 const chips = isControlled ? valueProp : uncontrolled;55 const [draft, setDraft] = useState("");56 const [highlight, setHighlight] = useState<number | null>(null);57 const [flash, setFlash] = useState<{ chip: string; token: number } | null>(58 null,59 );60 const [error, setError] = useState<string | null>(null);61 const [focused, setFocused] = useState(false);62 const [activeSuggestion, setActiveSuggestion] = useState(0);63 const [navigated, setNavigated] = useState(false);64 const [announcement, setAnnouncement] = useState("");65 const inputRef = useRef<HTMLInputElement>(null);66 const [scope, animate] = useAnimate<HTMLDivElement>();67 68 const full = max != null && chips.length >= max;69 const lower = new Set(chips.map((c) => c.toLowerCase()));70 const query = draft.trim().toLowerCase();71 const matches = suggestions72 .filter(73 (s) =>74 !lower.has(s.toLowerCase()) &&75 (!query || s.toLowerCase().includes(query)),76 )77 .slice(0, 6);78 const listOpen = focused && !full && !disabled && matches.length > 0;79 const showActive = query.length > 0 || navigated;80 const listId = `${uid}-list`;81 82 const setChips = useCallback(83 (next: string[]) => {84 if (!isControlled) setUncontrolled(next);85 onChange?.(next);86 },87 [isControlled, onChange],88 );89 90 const reject = (message: string) => {91 setError(message);92 if (!reduce && scope.current) {93 animate(94 scope.current,95 { x: [0, -6, 5, -3, 2, 0] },96 { duration: 0.36, ease: "easeOut" },97 );98 }99 };100 101 const addTokens = (tokens: string[]) => {102 if (disabled || tokens.length === 0) return;103 const seen = new Set(lower);104 const next = [...chips];105 for (const t of tokens) {106 if (max != null && next.length >= max) {107 reject(`Up to ${max} allowed`);108 break;109 }110 const key = t.toLowerCase();111 if (seen.has(key)) {112 // Point at the chip that already exists instead of silently ignoring.113 const existing = next.find((c) => c.toLowerCase() === key) ?? t;114 setFlash({ chip: existing, token: Date.now() });115 continue;116 }117 const message = validate?.(t);118 if (message) {119 reject(message);120 continue;121 }122 seen.add(key);123 next.push(t);124 }125 if (next.length !== chips.length) {126 setChips(next);127 setError(null);128 const added = next.slice(chips.length);129 setAnnouncement(`Added ${added.join(", ")}. ${next.length} total.`);130 }131 setDraft("");132 setHighlight(null);133 setActiveSuggestion(0);134 setNavigated(false);135 };136 137 const removeAt = (index: number) => {138 if (disabled) return;139 const chip = chips[index];140 if (chip === undefined) return;141 setChips(chips.filter((_, i) => i !== index));142 setError(null);143 setHighlight(null);144 setAnnouncement(`Removed ${chip}.`);145 };146 147 const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {148 const caretAtStart =149 e.currentTarget.selectionStart === 0 &&150 e.currentTarget.selectionEnd === 0;151 152 if (listOpen && (e.key === "ArrowDown" || e.key === "ArrowUp")) {153 e.preventDefault();154 const d = e.key === "ArrowDown" ? 1 : -1;155 setActiveSuggestion((i) =>156 navigated || query157 ? (i + d + matches.length) % matches.length158 : d > 0159 ? 0160 : matches.length - 1,161 );162 setNavigated(true);163 return;164 }165 if (166 e.key === "Enter" ||167 e.key === "," ||168 (e.key === "Tab" && draft.trim())169 ) {170 const pick =171 listOpen && showActive ? matches[activeSuggestion] : undefined;172 if (!pick && !draft.trim()) return;173 e.preventDefault();174 addTokens(pick ? [pick] : splitTokens(draft));175 return;176 }177 if (e.key === "Escape") {178 if (highlight !== null) setHighlight(null);179 else if (draft) setDraft("");180 return;181 }182 if (!caretAtStart || !chips.length) return;183 184 // Backspace highlights the last chip first, a second press removes it.185 if (e.key === "Backspace" || e.key === "Delete") {186 e.preventDefault();187 if (highlight !== null) removeAt(highlight);188 else if (e.key === "Backspace") setHighlight(chips.length - 1);189 } else if (e.key === "ArrowLeft") {190 e.preventDefault();191 setHighlight((h) => (h === null ? chips.length - 1 : Math.max(0, h - 1)));192 } else if (e.key === "ArrowRight" && highlight !== null) {193 e.preventDefault();194 setHighlight((h) => (h === null || h >= chips.length - 1 ? null : h + 1));195 }196 };197 198 return (199 <div className={cn("w-full", className)}>200 <div className="relative">201 <div202 ref={scope}203 onClick={() => inputRef.current?.focus()}204 className={cn(205 "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",206 "bg-(--color-paper) transition-shadow duration-200",207 error208 ? "shadow-[inset_0_0_0_1.5px_rgb(239_68_68/0.7)]"209 : focused210 ? "shadow-[inset_0_0_0_1.5px_var(--color-ink),0_0_0_4px_color-mix(in_oklab,var(--color-ink)_8%,transparent)]"211 : "shadow-[inset_0_0_0_1px_var(--color-rule)]",212 disabled && "cursor-not-allowed opacity-50",213 )}214 >215 <AnimatePresence initial={false} mode="popLayout">216 {chips.map((chip, i) => {217 const isHighlighted = highlight === i;218 const isFlashing = flash?.chip === chip;219 return (220 <motion.span221 key={chip}222 layout={reduce ? false : "position"}223 initial={224 reduce225 ? { opacity: 0 }226 : { opacity: 0, scale: 0.6, filter: "blur(4px)" }227 }228 animate={229 isFlashing && !reduce230 ? { opacity: 1, scale: [1, 1.1, 1], filter: "blur(0px)" }231 : { opacity: 1, scale: 1, filter: "blur(0px)" }232 }233 exit={234 reduce235 ? { opacity: 0 }236 : { opacity: 0, scale: 0.6, filter: "blur(4px)" }237 }238 transition={isFlashing ? { duration: 0.4 } : SPRING}239 onAnimationComplete={() => isFlashing && setFlash(null)}240 className={cn(241 "inline-flex h-8 max-w-full items-center gap-0.5 rounded-full pr-1 pl-3 text-[13px] font-medium",242 "transition-[background-color,color,box-shadow] duration-200",243 isHighlighted244 ? "bg-(--color-ink) text-(--color-paper)"245 : isFlashing246 ? "bg-amber-500/15 text-(--color-ink) shadow-[inset_0_0_0_1px_rgb(245_158_11/0.5)]"247 : "bg-(--color-paper-2) text-(--color-ink) shadow-[inset_0_0_0_1px_var(--color-rule)]",248 )}249 >250 <span className="truncate">{chip}</span>251 {!disabled ? (252 <button253 type="button"254 tabIndex={-1}255 aria-label={`Remove ${chip}`}256 onClick={(e) => {257 e.stopPropagation();258 removeAt(i);259 inputRef.current?.focus();260 }}261 className={cn(262 "flex size-6 shrink-0 items-center justify-center rounded-full transition-[background-color,transform] duration-150 outline-none active:scale-90",263 isHighlighted264 ? "hover:bg-(--color-paper)/20"265 : "text-(--color-neutral) hover:bg-(--color-ink)/10 hover:text-(--color-ink)",266 )}267 >268 <X className="size-3.5" strokeWidth={2} aria-hidden />269 </button>270 ) : null}271 </motion.span>272 );273 })}274 </AnimatePresence>275 276 <motion.input277 layout={reduce ? false : "position"}278 transition={SPRING}279 ref={inputRef}280 role="combobox"281 aria-label={label ?? placeholder}282 aria-expanded={listOpen}283 aria-controls={listOpen ? listId : undefined}284 aria-activedescendant={285 listOpen && showActive286 ? `${listId}-${activeSuggestion}`287 : undefined288 }289 aria-autocomplete="list"290 aria-invalid={!!error}291 aria-describedby={`${uid}-help`}292 value={draft}293 disabled={disabled}294 readOnly={full}295 placeholder={296 full ? "" : chips.length === 0 ? placeholder : "Add more…"297 }298 onChange={(e) => {299 setDraft(e.target.value);300 setHighlight(null);301 setError(null);302 setActiveSuggestion(0);303 setNavigated(false);304 }}305 onKeyDown={onKeyDown}306 onPaste={(e) => {307 const text = e.clipboardData.getData("text");308 if (/[,\n|]/.test(text)) {309 e.preventDefault();310 addTokens(splitTokens(text));311 }312 }}313 onFocus={() => setFocused(true)}314 onBlur={() => {315 setFocused(false);316 setHighlight(null);317 if (draft.trim()) addTokens(splitTokens(draft));318 }}319 className="h-8 min-w-[6rem] flex-1 bg-transparent px-1.5 text-[14px] text-(--color-ink) outline-none placeholder:text-(--color-neutral)"320 />321 </div>322 323 <AnimatePresence>324 {listOpen ? (325 <motion.div326 id={listId}327 role="listbox"328 aria-label="Suggestions"329 initial={330 reduce331 ? { opacity: 0 }332 : { opacity: 0, y: -4, scale: 0.98, filter: "blur(4px)" }333 }334 animate={{ opacity: 1, y: 0, scale: 1, filter: "blur(0px)" }}335 exit={336 reduce337 ? { opacity: 0 }338 : { opacity: 0, y: -4, scale: 0.98, filter: "blur(4px)" }339 }340 transition={{ duration: 0.18, ease: [0.23, 1, 0.32, 1] }}341 className={cn(342 "absolute inset-x-0 top-full z-20 mt-1.5 origin-top overflow-hidden rounded-[14px] p-1",343 "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",344 )}345 >346 {matches.map((s, i) => {347 const active = showActive && i === activeSuggestion;348 return (349 <div350 key={s}351 id={`${listId}-${i}`}352 role="option"353 aria-selected={active}354 onPointerDown={(e) => {355 e.preventDefault();356 addTokens([s]);357 }}358 onPointerEnter={() => {359 setActiveSuggestion(i);360 setNavigated(true);361 }}362 className={cn(363 "relative flex h-8 cursor-pointer items-center rounded-[10px] px-2.5 text-[13.5px] text-(--color-ink-2)",364 active && "text-(--color-ink)",365 )}366 >367 {active ? (368 <motion.span369 layoutId={`${uid}-suggestion`}370 transition={{371 type: "spring",372 bounce: 0,373 duration: 0.25,374 }}375 className="absolute inset-0 rounded-[10px] bg-(--color-paper-2)"376 />377 ) : null}378 <span className="relative">{s}</span>379 </div>380 );381 })}382 </motion.div>383 ) : null}384 </AnimatePresence>385 </div>386 387 <div388 id={`${uid}-help`}389 className="mt-1.5 flex min-h-4 items-center justify-between gap-3 px-1 text-[12px]"390 >391 <AnimatePresence initial={false} mode="popLayout">392 {error ? (393 <motion.span394 key="error"395 initial={{ opacity: 0, y: -4 }}396 animate={{ opacity: 1, y: 0 }}397 exit={{ opacity: 0, y: -4 }}398 className="text-red-600 dark:text-red-400"399 >400 {error}401 </motion.span>402 ) : (403 <motion.span404 key="hint"405 initial={{ opacity: 0 }}406 animate={{ opacity: 1 }}407 exit={{ opacity: 0 }}408 className="text-(--color-neutral)"409 >410 {full ? "Limit reached" : "Enter or comma to add"}411 </motion.span>412 )}413 </AnimatePresence>414 {max != null ? (415 <span416 className={cn(417 "tabular-nums transition-colors",418 full ? "text-(--color-ink)" : "text-(--color-neutral)",419 )}420 >421 {chips.length}/{max}422 </span>423 ) : null}424 </div>425 426 <div role="status" aria-live="polite" className="sr-only">427 {announcement}428 </div>429 </div>430 );431}
Adjust import paths according to your folder structure.
Basic Usage
tsx
1import { ChipInput } from "@/components/ui/chip-input";2 3const [tags, setTags] = useState(["billing"]);4 5<ChipInput6 value={tags}7 onChange={setTags}8 label="Ticket labels"9 max={6}10 suggestions={["billing", "bug", "design", "infra", "mobile"]}11 validate={(t) => (/\s/.test(t) ? "Use single words" : null)}12/>
Props
| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| value / defaultValue | string[] | No | — | Controlled or initial chips. |
| onChange | (value: string[]) => void | No | — | Fires with the new list after every add or remove. |
| suggestions | string[] | No | — | Autocomplete options. Ones already added are hidden; the rest filter as you type. |
| validate | (chip: string) => string | null | void | No | — | Return a message to reject a chip. It shows under the field until the next edit. |
| max | number | No | — | Most chips allowed. Shows a counter and blocks further adds once reached. |
| placeholder / label | string | No | "Add tag…" | Placeholder text, and the field's accessible name (defaults to the placeholder). |
| disabled / className | boolean / string | No | — | Disable the field, or add classes to the wrapper. |
Best Practices
- Matching is case-insensitive, so "Billing" and "billing" count as the same chip.
- Use
validatefor format rules andsuggestionsto steer people toward existing labels. - Leave room below the field for the suggestion list, or place it where the list can overlap content.
- Adds and removes are announced to screen readers.