Tag input
Type and press Enter or comma to turn words into chips, Backspace to edit the last one, and pick from suggestions as you go.
"use client";
import { useId, useRef, useState, type KeyboardEvent } from "react";
import "./tag-input.css";
type TagInputProps = {
initial?: string[];
suggestions?: string[];
max?: number;
theme?: "light" | "dark";
};
const DEFAULT_SUGGESTIONS = [
"Branding",
"Motion",
"Typography",
"Illustration",
"Web design",
"3D",
"Product",
"Packaging",
"UX research",
"Photography",
];
/**
* TagInput
* - Enter, comma or Tab adds the typed text; duplicates are ignored (case-insensitive).
* - Backspace in an empty field pulls the last chip back into the field for editing.
* - Arrow keys move through suggestions (a listbox, combobox pattern).
*/
export function TagInput({
initial = ["Branding", "Motion"],
suggestions = DEFAULT_SUGGESTIONS,
max = 6,
theme = "light",
}: TagInputProps) {
const id = useId();
const [tags, setTags] = useState(initial);
const [text, setText] = useState("");
const [active, setActive] = useState(0);
const [open, setOpen] = useState(false);
const [picked, setPicked] = useState(false); // true once the arrows chose a suggestion
const input = useRef<HTMLInputElement>(null);
const has = (t: string) =>
tags.some((x) => x.toLowerCase() === t.toLowerCase());
const matches = suggestions
.filter(
(s) => !has(s) && s.toLowerCase().includes(text.trim().toLowerCase()),
)
.slice(0, 5);
const full = tags.length >= max;
const add = (raw: string) => {
const t = raw.trim().replace(/,$/, "");
if (!t || has(t) || full) return;
setTags((x) => [...x, t]);
setText("");
setActive(0);
setPicked(false);
};
const remove = (t: string) => {
setTags((x) => x.filter((y) => y !== t));
input.current?.focus();
};
const onKey = (e: KeyboardEvent<HTMLInputElement>) => {
const showList = open && matches.length > 0;
if (e.key === "ArrowDown" && showList) {
e.preventDefault();
setActive((a) => (picked ? (a + 1) % matches.length : 0));
setPicked(true);
} else if (e.key === "ArrowUp" && showList) {
e.preventDefault();
setActive((a) => (a - 1 + matches.length) % matches.length);
setPicked(true);
} else if (e.key === "Enter" || e.key === ",") {
e.preventDefault();
// A suggestion chosen with the arrows wins; otherwise add exactly what was typed.
add(showList && picked ? matches[active] : text);
} else if (e.key === "Tab" && text.trim()) {
e.preventDefault();
add(text);
} else if (e.key === "Backspace" && text === "" && tags.length) {
e.preventDefault();
const last = tags[tags.length - 1];
setTags((x) => x.slice(0, -1));
setText(last);
} else if (e.key === "Escape") setOpen(false);
};
return (
<div className="gu-tags" data-theme={theme}>
<label htmlFor={id}>Skills</label>
<div className="gu-tags__box" onClick={() => input.current?.focus()}>
<ul className="gu-tags__list" aria-label="Selected skills">
{tags.map((t) => (
<li key={t} className="gu-tags__chip">
{t}
<button
type="button"
aria-label={`Remove ${t}`}
onClick={() => remove(t)}
>
<svg viewBox="0 0 12 12" aria-hidden="true">
<path d="m3 3 6 6M9 3 3 9" />
</svg>
</button>
</li>
))}
</ul>
<input
ref={input}
id={id}
value={text}
disabled={full}
placeholder={
full
? `That's ${max}, the max`
: tags.length
? "Add another…"
: "Type a skill…"
}
role="combobox"
aria-expanded={open && matches.length > 0}
aria-controls={`${id}-list`}
aria-activedescendant={
open && picked && matches.length ? `${id}-opt-${active}` : undefined
}
aria-autocomplete="list"
onChange={(e) => {
const v = e.target.value;
if (v.endsWith(",")) add(v);
else {
setText(v);
setActive(0);
setPicked(false);
setOpen(true);
}
}}
onKeyDown={onKey}
onFocus={() => setOpen(true)}
onBlur={() => setTimeout(() => setOpen(false), 120)}
/>
</div>
{open && matches.length > 0 && !full && (
<ul
className="gu-tags__menu"
id={`${id}-list`}
role="listbox"
aria-label="Suggestions"
>
{matches.map((m, i) => (
<li
key={m}
id={`${id}-opt-${i}`}
role="option"
aria-selected={picked && i === active}
onMouseDown={(e) => e.preventDefault()}
onMouseEnter={() => {
setActive(i);
setPicked(true);
}}
onClick={() => add(m)}
>
{m}
</li>
))}
</ul>
)}
<p className="gu-tags__hint">
{tags.length}/{max} · Enter or comma to add, Backspace to edit the last
one
</p>
</div>
);
}
Paste this into ChatGPT, Claude, Cursor, v0, Lovable or Bolt. It describes the layout, motion, colors and accessibility and includes the code, so the AI can rebuild it in any framework.
# Build this UI piece: Tag input
You are a senior front-end engineer. Recreate the piece below in my project. If I don't say which framework I use, ask once, then build it in that framework (React, Vue, Svelte, Angular, Astro, plain HTML/CSS/JS or anything else). Keep the behavior, motion, colors, spacing and accessibility exactly as described. Keep the code clean and commented for beginners.
## What it is
A chip/tag input: typed words become pill chips, with a suggestion list you can navigate by keyboard, a remove button on every chip and a max count.
## Layout and look
- Bold label, then a 56px+ field (radius 16px, 1.5px border) that wraps chips and the text input together.
- Chips: 36px pills, Ink background with Cream text (inverted in dark), a 28px round × button that turns orange on hover.
- Suggestion menu below the field: white card, radius 16px, 44px rows; the active row is orange with dark text.
- Hint line: "2/6 · Enter or comma to add, Backspace to edit the last one".
## Behavior and motion
1. Enter, comma or Tab adds the text. Duplicates (case-insensitive) are ignored. Max reached: the input disables with a message.
2. Backspace in an empty input removes the last chip and puts its text back into the input for editing.
3. ArrowUp/Down move the active suggestion; Enter with an empty input picks it; click picks too.
4. Chips pop in with a springy scale (350ms, overshoot easing). The menu drops in 6px.
## Touch
Each chip has its own remove button; suggestions are 44px.
## Accessibility
- Input is a combobox with aria-expanded, aria-controls, aria-activedescendant; suggestions are a listbox with options.
- Chips are a labelled list; each remove button says "Remove {tag}".
- prefers-reduced-motion: no pop or drop animation.
## Props
initial, suggestions, max, theme.
## Reference implementation
The original is written in React with one plain CSS file. Dependencies: none (plain React and CSS). Translate it faithfully; do not add new libraries unless my framework needs them.
### TagInput.tsx
```tsx
"use client";
import { useId, useRef, useState, type KeyboardEvent } from "react";
import "./tag-input.css";
type TagInputProps = {
initial?: string[];
suggestions?: string[];
max?: number;
theme?: "light" | "dark";
};
const DEFAULT_SUGGESTIONS = [
"Branding",
"Motion",
"Typography",
"Illustration",
"Web design",
"3D",
"Product",
"Packaging",
"UX research",
"Photography",
];
/**
* TagInput
* - Enter, comma or Tab adds the typed text; duplicates are ignored (case-insensitive).
* - Backspace in an empty field pulls the last chip back into the field for editing.
* - Arrow keys move through suggestions (a listbox, combobox pattern).
*/
export function TagInput({
initial = ["Branding", "Motion"],
suggestions = DEFAULT_SUGGESTIONS,
max = 6,
theme = "light",
}: TagInputProps) {
const id = useId();
const [tags, setTags] = useState(initial);
const [text, setText] = useState("");
const [active, setActive] = useState(0);
const [open, setOpen] = useState(false);
const [picked, setPicked] = useState(false); // true once the arrows chose a suggestion
const input = useRef<HTMLInputElement>(null);
const has = (t: string) =>
tags.some((x) => x.toLowerCase() === t.toLowerCase());
const matches = suggestions
.filter(
(s) => !has(s) && s.toLowerCase().includes(text.trim().toLowerCase()),
)
.slice(0, 5);
const full = tags.length >= max;
const add = (raw: string) => {
const t = raw.trim().replace(/,$/, "");
if (!t || has(t) || full) return;
setTags((x) => [...x, t]);
setText("");
setActive(0);
setPicked(false);
};
const remove = (t: string) => {
setTags((x) => x.filter((y) => y !== t));
input.current?.focus();
};
const onKey = (e: KeyboardEvent<HTMLInputElement>) => {
const showList = open && matches.length > 0;
if (e.key === "ArrowDown" && showList) {
e.preventDefault();
setActive((a) => (picked ? (a + 1) % matches.length : 0));
setPicked(true);
} else if (e.key === "ArrowUp" && showList) {
e.preventDefault();
setActive((a) => (a - 1 + matches.length) % matches.length);
setPicked(true);
} else if (e.key === "Enter" || e.key === ",") {
e.preventDefault();
// A suggestion chosen with the arrows wins; otherwise add exactly what was typed.
add(showList && picked ? matches[active] : text);
} else if (e.key === "Tab" && text.trim()) {
e.preventDefault();
add(text);
} else if (e.key === "Backspace" && text === "" && tags.length) {
e.preventDefault();
const last = tags[tags.length - 1];
setTags((x) => x.slice(0, -1));
setText(last);
} else if (e.key === "Escape") setOpen(false);
};
return (
<div className="gu-tags" data-theme={theme}>
<label htmlFor={id}>Skills</label>
<div className="gu-tags__box" onClick={() => input.current?.focus()}>
<ul className="gu-tags__list" aria-label="Selected skills">
{tags.map((t) => (
<li key={t} className="gu-tags__chip">
{t}
<button
type="button"
aria-label={`Remove ${t}`}
onClick={() => remove(t)}
>
<svg viewBox="0 0 12 12" aria-hidden="true">
<path d="m3 3 6 6M9 3 3 9" />
</svg>
</button>
</li>
))}
</ul>
<input
ref={input}
id={id}
value={text}
disabled={full}
placeholder={
full
? `That's ${max}, the max`
: tags.length
? "Add another…"
: "Type a skill…"
}
role="combobox"
aria-expanded={open && matches.length > 0}
aria-controls={`${id}-list`}
aria-activedescendant={
open && picked && matches.length ? `${id}-opt-${active}` : undefined
}
aria-autocomplete="list"
onChange={(e) => {
const v = e.target.value;
if (v.endsWith(",")) add(v);
else {
setText(v);
setActive(0);
setPicked(false);
setOpen(true);
}
}}
onKeyDown={onKey}
onFocus={() => setOpen(true)}
onBlur={() => setTimeout(() => setOpen(false), 120)}
/>
</div>
{open && matches.length > 0 && !full && (
<ul
className="gu-tags__menu"
id={`${id}-list`}
role="listbox"
aria-label="Suggestions"
>
{matches.map((m, i) => (
<li
key={m}
id={`${id}-opt-${i}`}
role="option"
aria-selected={picked && i === active}
onMouseDown={(e) => e.preventDefault()}
onMouseEnter={() => {
setActive(i);
setPicked(true);
}}
onClick={() => add(m)}
>
{m}
</li>
))}
</ul>
)}
<p className="gu-tags__hint">
{tags.length}/{max} · Enter or comma to add, Backspace to edit the last
one
</p>
</div>
);
}
```
### tag-input.css
```css
/* TagInput: change these colors to match your brand. */
.gu-tags {
--field: #fbf8f2;
--text: #0e0e10;
--muted: #57534b;
--line: rgb(14 14 16 / 0.18);
--chip: #0e0e10;
--chip-text: #f3eee3;
--hot: #ff5a1f;
--focus: #2b35ff;
--menu: #ffffff;
position: relative;
display: grid;
gap: 8px;
width: min(100%, 440px);
color: var(--text);
font-family: system-ui, sans-serif;
}
.gu-tags[data-theme="dark"] {
--field: #18181b;
--text: #f3eee3;
--muted: #aea89c;
--line: rgb(243 238 227 / 0.18);
--chip: #f3eee3;
--chip-text: #0e0e10;
--focus: #d7ff3a;
--menu: #1f1f23;
}
.gu-tags > label {
font-weight: 800;
}
.gu-tags__box {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
min-height: 56px;
padding: 8px;
border: 1.5px solid var(--line);
border-radius: 16px;
background: var(--field);
cursor: text;
transition:
border-color 0.2s,
box-shadow 0.2s;
}
.gu-tags__box:focus-within {
border-color: var(--focus);
box-shadow: 0 0 0 4px color-mix(in srgb, var(--focus) 18%, transparent);
}
.gu-tags__list {
display: contents;
list-style: none;
}
.gu-tags__chip {
display: inline-flex;
align-items: center;
gap: 2px;
height: 36px;
padding: 0 4px 0 12px;
border-radius: 999px;
background: var(--chip);
color: var(--chip-text);
font-size: 0.9rem;
font-weight: 700;
animation: gu-tags-pop 0.35s cubic-bezier(0.34, 1.56, 0.64, 1);
}
@keyframes gu-tags-pop {
from {
transform: scale(0.4);
opacity: 0;
}
}
.gu-tags__chip button {
display: grid;
place-items: center;
width: 28px;
height: 28px;
border: 0;
border-radius: 50%;
background: none;
color: inherit;
cursor: pointer;
opacity: 0.7;
}
.gu-tags__chip button:hover {
background: var(--hot);
color: #0e0e10;
opacity: 1;
}
.gu-tags__chip button:focus-visible {
outline: 2px solid var(--focus);
opacity: 1;
}
.gu-tags__chip svg {
width: 12px;
stroke: currentColor;
stroke-width: 2;
stroke-linecap: round;
}
.gu-tags input {
flex: 1;
min-width: 8em;
height: 36px;
padding: 0 6px;
border: 0;
outline: none;
background: none;
color: inherit;
font: inherit;
}
.gu-tags input::placeholder {
color: var(--muted);
}
.gu-tags__menu {
position: absolute;
top: calc(100% - 22px);
left: 0;
right: 0;
z-index: 5;
margin: 0;
padding: 6px;
border: 1px solid var(--line);
border-radius: 16px;
background: var(--menu);
list-style: none;
box-shadow: 0 20px 40px -16px rgb(0 0 0 / 0.3);
animation: gu-tags-drop 0.2s ease-out;
}
@keyframes gu-tags-drop {
from {
transform: translateY(-6px);
opacity: 0;
}
}
.gu-tags__menu li {
display: flex;
align-items: center;
min-height: 44px;
padding: 0 12px;
border-radius: 10px;
font-weight: 600;
cursor: pointer;
}
.gu-tags__menu li[aria-selected="true"] {
background: var(--hot);
color: #0e0e10;
}
.gu-tags__hint {
margin: 0;
color: var(--muted);
font-size: 0.8rem;
}
@media (prefers-reduced-motion: reduce) {
.gu-tags__chip,
.gu-tags__menu {
animation: none;
}
}
```
You might also want
Next piece: Testimonial wallDate range picker
Components, advanced
One-time code input
Components, intermediate
Search with suggestions
Components, intermediate