Tag Input That Adds on Enter or Comma and Removes With Backspace
A skills field from a job post form where each word becomes an indigo chip. Enter or a comma turns the typed text into a tag, Backspace in an empty field takes the last one off, and a pasted list like figma, sketch, framer splits into three chips at once. The chips wrap onto new lines on a phone and the whole box stays one tap target.
Code
import { useRef, useState, type KeyboardEvent } from "react";
// Starting tags and the field label. Change these for your own form.
const START = ["product design", "figma", "remote"];
const LABEL = "Skills for this role";
export default function TagInputAddsOnEnterOrComma() {
const [tags, setTags] = useState<string[]>(START);
const [text, setText] = useState("");
const [note, setNote] = useState("");
const field = useRef<HTMLInputElement>(null);
// Adds every comma separated piece, skipping blanks and repeats.
const addAll = (raw: string) => {
const next = [...tags];
const added: string[] = [];
for (const part of raw.split(/[,\n]/)) {
const t = part.trim().toLowerCase();
if (!t) continue;
if (next.includes(t)) { setNote(`${t} is already in the list`); continue; }
next.push(t);
added.push(t);
}
setTags(next);
setText("");
if (added.length) setNote(`Added ${added.join(", ")}`);
};
const remove = (t: string) => {
setTags(tags.filter((x) => x !== t));
setNote(`Removed ${t}`);
field.current?.focus();
};
const onKey = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter" || e.key === ",") {
e.preventDefault();
addAll(text);
} else if (e.key === "Backspace" && text === "" && tags.length) {
remove(tags[tags.length - 1]);
}
};
return (
<section className="bg-stone-100 px-4 py-16 sm:py-20">
<div className="mx-auto max-w-xl rounded-2xl border border-stone-200 bg-white p-6 shadow-sm sm:p-8">
<h2 className="text-lg font-semibold tracking-tight text-stone-900">New job post</h2>
<p className="mt-1 text-sm text-stone-600">Junior product designer, Halden Studio</p>
<label htmlFor="tiec-field" className="mt-6 block text-sm font-medium text-stone-800">{LABEL}</label>
<div
onClick={() => field.current?.focus()}
className="mt-2 flex min-h-[52px] flex-wrap items-center gap-2 rounded-xl border border-stone-300 bg-white px-2.5 py-2 transition-colors focus-within:border-indigo-600 focus-within:ring-4 focus-within:ring-indigo-100"
>
<ul className="contents" aria-label="Added skills">
{tags.map((t) => (
<li key={t} className="flex h-8 items-center gap-1 rounded-lg bg-indigo-50 pl-3 pr-1 text-sm font-medium text-indigo-900">
{t}
<button
type="button"
aria-label={`Remove ${t}`}
onClick={(e) => { e.stopPropagation(); remove(t); }}
className="grid h-6 w-6 place-items-center rounded-md text-indigo-700 hover:bg-indigo-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-600"
>
<svg viewBox="0 0 20 20" width="14" height="14" aria-hidden="true"><path d="M5 5l10 10M15 5L5 15" stroke="currentColor" strokeWidth="2" strokeLinecap="round" /></svg>
</button>
</li>
))}
</ul>
<input
id="tiec-field"
ref={field}
value={text}
onChange={(e) => (e.target.value.includes(",") ? addAll(e.target.value) : setText(e.target.value))}
onKeyDown={onKey}
onBlur={() => text.trim() && addAll(text)}
aria-describedby="tiec-hint"
placeholder={tags.length ? "Add another" : "Type a skill"}
className="h-8 min-w-[8rem] flex-1 bg-transparent px-1 text-sm text-stone-900 placeholder:text-stone-500 focus:outline-none"
/>
</div>
<p id="tiec-hint" className="mt-2 text-xs text-stone-600">Press Enter or a comma to add. Backspace in an empty field removes the last skill.</p>
<p aria-live="polite" className="sr-only">{note}</p>
<input type="hidden" name="skills" value={tags.join(",")} />
<div className="mt-6 flex items-center justify-between border-t border-stone-200 pt-5">
<span className="text-sm text-stone-600">{tags.length} {tags.length === 1 ? "skill" : "skills"}</span>
<button type="button" className="h-10 rounded-lg bg-stone-900 px-4 text-sm font-medium text-white hover:bg-stone-800 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-600 focus-visible:ring-offset-2">Save draft</button>
</div>
</div>
</section>
);
}
Install with one command: npx shadcn@latest add https://we.inc/r/tag-input-that-adds-on-enter-or-comma-and-removes-with-backspace.json
When to use it
- People enter free words that do not come from a fixed list, such as skills, ingredients or keywords for a listing.
- You want the smallest tag field that still behaves the way people expect from mail and project tools.
- A form posts normally to a server and needs the tags as one comma separated value.
- You need a starting point to extend with suggestions, limits or colour later without rewriting the keyboard logic.
How to customize it
- Edit `START` for the tags that show on load and `LABEL` for the field name; the plain version reads its starting tags from the hidden input value.
- Change the chip colours through `bg-indigo-50` and `text-indigo-900`, or `--tiec-chip` and `--tiec-chip-ink` in the plain CSS.
- Remove `.toLowerCase()` in `addAll` if tags should keep the capitals people type, such as brand names.
- Add Tab to the keys that create a tag in `onKey` if your form has nothing else to tab to after this field.
Accessibility
- Each chip has a real remove button labelled with its word, such as Remove figma, so a keyboard user can delete a tag from the middle.
- A polite live region says Added or Removed after each change, and repeats are explained instead of being dropped without a word.
- The hint about Enter, comma and Backspace is tied to the field with aria-describedby, so it is read when the field gets focus.
Questions
Why does Backspace only remove a tag when the field is empty?
If it removed a tag on every press, people fixing a typo in the word they are typing would lose a chip by accident. Checking for an empty value first means Backspace edits text as normal and only reaches the chips once there is nothing left to delete.
What happens when someone pastes several words?
The change handler sees the comma in the new value and hands the whole string to the same add function that Enter uses. It splits on commas and line breaks, trims each part and skips blanks and repeats.
Does the typed text get lost if the person clicks away?
No. On blur, any text still in the field is turned into a tag, which matches what most people expect when they move on to the next question.
How do I read the tags when the form is submitted?
In React, read the `tags` array from state in your submit handler. With a plain form post, the hidden input named skills carries the list as comma separated text.
Can I stop people adding very long tags?
Add a maxLength to the input, for example 30, and check the length inside the add function so pasted text obeys the same rule. Show the reason in the live region when a piece is rejected.
Related: React Tag Input with Autocomplete Suggestions, Paste Support and Coloured Category Chips, Tag Input With Arrow Key Autocomplete Suggestion List, Email Recipient Tag Input That Validates Each Address.
More inputs or all free UI components. Build your site free to have a full site built around it.
More in Inputs
- Thumbwheel Number Picker with Rolling Digit Drums and Knurled Wheels
- Twin-Bell Alarm Clock with an Alarm Hand You Drag to Set and Bells That Shake When It Rings
- Watercolour Pan Tin Colour Picker with a Sable Brush That Loads a Pan and Blooms a Wash into Cotton Paper
- Wooden Block Perpetual Calendar Date Picker with Number Cubes You Lift, Turn and Drop into a Walnut Cradle
- Wooden Type Verification Code Input Where Number Blocks Drop into a Brass Composing Stick and a Wedge Locks the Line
- Brass and Perspex Protractor Angle Input with a Swinging Arm That Rules the Angle in Pencil
- Brass Letterbox File Upload with a Sprung Flap That Swallows Envelopes and Rattles Shut
- Brass Mixing Desk Fader in WebGL with Weighted Detents, an Engraved Decibel Plate and a Backlit VU Needle
Product
Who It's For
- For Agencies
- For Freelancers
- For Hosting Providers
- For SaaS Platforms
- For Startups
- For Financial Services
- For Healthcare
Features
Resources
- Blog
- Help Center
- Free Business Tools
- Free UI Components
- Website Templates
- Template Collections
- Website Examples
- Guides
- Comparisons
- Alternatives
- Best Lists
- Reviews
- Pricing Guides
- Use Cases
- Glossary & Guides
- Integrations
- Developers
- Benchmark
- Windows App