React Tag Input Component With Tailwind
Build a tag input in React and Tailwind CSS: add on Enter or comma, remove with Backspace, paste lists, accessible chips, plus animated tag inputs and pickers to copy.
A tag input turns typed words into removable chips: type a word, press Enter, and it becomes a tag. It is used for skills, topics, email recipients, filters and keywords. The basic version takes a few lines. The parts that make it feel right are the ones people forget: Backspace to remove the last tag, no duplicates, pasting a whole list, not submitting the surrounding form on Enter, and chips a keyboard user can actually reach.
This guide builds a controlled tag input in React and Tailwind CSS with no library, then shows animated tag inputs and tag pickers when a plain field is not the right fit.
How a tag input behaves
- Typing goes into an ordinary text input.
- Enter or comma commits the typed text as a tag and clears the input.
- Backspace on an empty input removes the most recent tag.
- Each tag has its own remove button.
- Clicking anywhere in the box focuses the input, so the whole field feels like one control.
The React and Tailwind component
The component is controlled: the parent owns the list, and the component asks it to change.
"use client";
import { useRef, useState, type ClipboardEvent, type KeyboardEvent } from "react";
export function TagInput({
value,
onChange,
placeholder = "Add a tag",
max = 10,
name,
}: {
value: string[];
onChange: (tags: string[]) => void;
placeholder?: string;
max?: number;
name?: string;
}) {
const [draft, setDraft] = useState("");
const inputRef = useRef<HTMLInputElement>(null);
function add(raw: string) {
const next = [...value];
for (const part of raw.split(",")) {
const tag = part.trim();
if (!tag || next.length >= max) continue;
if (next.some((t) => t.toLowerCase() === tag.toLowerCase())) continue;
next.push(tag);
}
if (next.length !== value.length) onChange(next);
setDraft("");
}
function onKeyDown(e: KeyboardEvent<HTMLInputElement>) {
if (e.nativeEvent.isComposing) return; // let an input method finish a word first
if (e.key === "Enter" || e.key === ",") {
e.preventDefault(); // never submit the surrounding form
add(draft);
} else if (e.key === "Backspace" && draft === "" && value.length > 0) {
onChange(value.slice(0, -1));
}
}
function onPaste(e: ClipboardEvent<HTMLInputElement>) {
const text = e.clipboardData.getData("text");
if (/[,\n]/.test(text)) {
e.preventDefault();
add(text.replace(/\n/g, ","));
}
}
return (
<div
role="group"
aria-label="Tags"
onClick={() => inputRef.current?.focus()}
className="flex min-h-11 w-full max-w-md cursor-text flex-wrap items-center gap-1.5 rounded-xl border border-zinc-200 bg-white px-2 py-1.5 focus-within:border-zinc-400 focus-within:ring-2 focus-within:ring-zinc-900/10"
>
{value.map((tag) => (
<span
key={tag}
className="inline-flex items-center gap-1 rounded-lg bg-zinc-100 py-1 pl-2.5 pr-1 text-sm text-zinc-800"
>
{tag}
<button
type="button"
aria-label={`Remove ${tag}`}
onClick={() => onChange(value.filter((t) => t !== tag))}
className="grid size-5 place-items-center rounded-md text-zinc-500 outline-none hover:bg-zinc-200 hover:text-zinc-900 focus-visible:ring-2 focus-visible:ring-zinc-900/30"
>
<svg
aria-hidden="true"
viewBox="0 0 20 20"
fill="none"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
className="size-3"
>
<path d="m5 5 10 10M15 5 5 15" />
</svg>
</button>
</span>
))}
<input
ref={inputRef}
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={onKeyDown}
onPaste={onPaste}
onBlur={() => draft.trim() && add(draft)}
disabled={value.length >= max}
placeholder={value.length === 0 ? placeholder : ""}
aria-label="New tag"
className="min-w-24 flex-1 bg-transparent px-1 py-1 text-sm text-zinc-900 outline-none placeholder:text-zinc-400"
/>
{name && <input type="hidden" name={name} value={value.join(",")} />}
</div>
);
}
Use it by keeping the list in state:
"use client";
import { useState } from "react";
import { TagInput } from "./tag-input";
export function SkillsField() {
const [skills, setSkills] = useState(["React", "Tailwind"]);
return <TagInput value={skills} onChange={setSkills} placeholder="Add a skill" name="skills" />;
}
Notes on the choices in this code:
e.preventDefault()on Enter. Inside a form, Enter would submit it. Stopping the default makes Enter mean "add this tag" and nothing else.isComposingcheck. People typing Japanese, Chinese or Korean use an input method, and Enter confirms a word there. Without this check, the tag would be added half way through composing.- Case-insensitive duplicates.
Reactandreactare the same tag, so the second is ignored. - Paste handling. If the pasted text has commas or line breaks it is split into several tags at once, so pasting a spreadsheet column just works. A single word pastes into the input as normal.
onBlurcommits the draft. Someone who types a word and clicks elsewhere would otherwise lose it without noticing.- Real buttons for removal. Each chip has a
buttonwith anaria-labelsuch as "Remove React", so the tags are reachable by Tab and announced properly. A cross drawn on aspanis not. - A hidden input with a
namesends the tags with a normal form post as one comma-separated value. Skip it if you submit with JavaScript. focus-withinon the wrapper. The border and ring show on the box when the inner input has focus, so the whole field looks like one control.
Things to decide for your product
- A suggestion list. Show matching options under the input and let Arrow keys choose one. If tags must come from a fixed set, validate on add and show why a tag was rejected.
- A maximum. The
maxprop stops the list at a limit. Tell people why the field stopped accepting input, rather than only disabling it. - Editing a tag. Most products only add and remove. If you need editing, turn a chip back into an input on double-click.
- Character limits and trimming. Cap the length of one tag and strip leading and trailing spaces, as the code does for spaces.
Tag inputs and tag pickers with more personality
A plain chip field is the right default for a form. When tags are the main interaction, such as picking interests during onboarding or adding keywords to a post, the way a tag appears and leaves can carry real delight. Two finished React components do that:
- Bubble Tags is a tag input where every tag is a soap bubble. Type a word and press Enter, and a wand blows a bubble with the word inside that drifts up to join the others. Tapping a bubble pops it, and Backspace in the empty field pops the newest. Every bubble is a real button and the field is a real input, so keyboards and screen readers still get a plain list. Bubble Tags is a Pro component.
- Tag Pit is an interests picker where every tag is a physical pill dropped into a tray. Grab and throw the pills, shake the tray, and tap one to pick it. Continue unlocks once enough are picked. Tag Pit is a Pro component.
Install either with the shadcn CLI, for example npx shadcn@latest add @nexus-labs/bubble-tags; each component page says exactly what it adds. For more fields and controls, browse the input and control components category and the input components collection. If you want a search field to go with your filters, see our guide to a React input with a search icon.
Frequently asked questions
How do I create a tag input in React?
Keep the tags in an array in state, show them as chips, and keep the typed text in a separate state value. On Enter or comma, trim the text, skip it if it is empty or already present, add it to the array and clear the input. The component above is a complete controlled version.
How do I add tags on Enter and comma in React?
Handle onKeyDown on the input. When the key is Enter or comma, call preventDefault() and add the draft. Calling preventDefault() also stops Enter from submitting a surrounding form.
How do I remove the last tag with Backspace?
In onKeyDown, if the key is Backspace and the input is empty, remove the last item of the array. Only do it when the draft is empty, so Backspace still edits what is being typed.
How do I stop duplicate tags?
Compare the new tag to the existing ones, ignoring case, before adding it. Skip it silently, or show a short message if the duplicate was probably a mistake.
How do I make a tag input accessible?
Give the input a label, give each remove button an aria-label that names its tag, use real button elements for removal, and keep a visible focus ring on every control. Do not rely on colour or a drawn cross alone.
How do I submit tags with a form?
Either keep them in state and send them with JavaScript, or add a hidden input with a name and the tags joined by commas so a normal form post includes them.