How to Build a Tag Input Field in React
A tag input is straightforward to write if you keep the array of tags and the text being typed in separate state. When you press Enter or ",", the typed text is added to the tag array. A tag is removed from the array when you click its × button or press Backspace while the input is empty.
There are three things to watch for. The Enter that confirms IME composition for Japanese input must not create a tag. Enter must not submit the form. After a tag is removed, focus must return to the input. For each of these, I compared the correct code with a version that leaves out the handling, and checked what happens.
The test environment was Ubuntu 24.04, Node.js 22.22.0, and Chromium 153. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx file with tsc, transpiled it with esbuild, and used Playwright to drive Chromium and check the tag list, the input value, and the focus position. I did not use a real IME. I reproduced Japanese composition with Chrome DevTools Protocol commands. I did not test Firefox, Safari, mobile browsers, or screen reader announcements.

- 1. Keep the tag array and the input text in separate state
- 2. Turn input into tags with Enter and ","
- 3. Do not create a tag from the Enter that confirms Japanese composition
- 4. Remove the last tag with Backspace when the input is empty
- 5. Name each delete button so it says which tag it removes
- 6. Turn pasted text with separators into tags all at once
- 7. When sending with a form, put the tags in hidden inputs
- 8. Without preventDefault, Enter submits the form
Keep the tag array and the input text in separate state
The whole component looks like this. The tag array tags is received from the parent. To change it, the component calls onChange with a new array. The text being typed, text, is kept only inside this component.
import { useId, useRef, useState } from 'react';
type Props = {
label: string;
tags: string[];
onChange: (tags: string[]) => void;
};
// Split on ",", "、", or newlines, trim surrounding spaces, and drop empty items
export function splitTags(text: string) {
return text
.split(/[,、\n]/)
.map((t) => t.trim())
.filter(Boolean);
}
export function TagInput({ label, tags, onChange }: Props) {
const [text, setText] = useState('');
const inputRef = useRef<HTMLInputElement>(null);
const id = useId();
function addTags(candidates: string[]) {
const next = [...tags];
for (const tag of candidates) {
// Treat tags that differ only in letter case as the same tag
if (!next.some((t) => t.toLowerCase() === tag.toLowerCase())) next.push(tag);
}
if (next.length !== tags.length) onChange(next);
setText('');
}
function removeTag(index: number) {
onChange(tags.filter((_, i) => i !== index));
// The delete button that was pressed disappears, so move focus back to the input
inputRef.current?.focus();
}
function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
// Leave keys pressed during IME composition to the IME
if (e.nativeEvent.isComposing || e.keyCode === 229) return;
if (e.key === 'Enter' || e.key === ',') {
// Stop form submission and stop "," from being typed into the input
e.preventDefault();
addTags(splitTags(text));
} else if (e.key === 'Backspace' && text === '' && tags.length > 0) {
removeTag(tags.length - 1);
}
}
function handlePaste(e: React.ClipboardEvent<HTMLInputElement>) {
const pasted = e.clipboardData.getData('text');
// Only turn pasted text into tags when it contains a separator
if (!/[,、\n]/.test(pasted)) return;
e.preventDefault();
addTags(splitTags(text + pasted));
}
return (
<div className="field">
<label htmlFor={id}>{label}</label>
<div className="tag-input" onClick={() => inputRef.current?.focus()}>
<ul className="tags">
{tags.map((tag, i) => (
<li key={tag} className="tag">
{tag}
<button type="button" aria-label={`${tag} を削除`} onClick={() => removeTag(i)}>
×
</button>
</li>
))}
</ul>
<input
id={id}
ref={inputRef}
value={text}
onChange={(e) => setText(e.target.value)}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
placeholder={tags.length === 0 ? 'Enter か , で追加' : ''}
/>
</div>
</div>
);
}
addTags does not add a tag that already exists, including one that differs only in letter case. This keeps tag strings unique within the array, so they can be used directly as key. The React documentation on keys says that keys must be unique among sibling elements. It also warns that using array indexes as keys can cause confusing bugs when adding or removing items changes the order. Tags can be removed from the middle of the list, so I used the tag string instead of the index.
The <label> and <input> are linked by an ID created with useId. According to the useId page, the IDs stay unique even when the same component appears several times on the screen.
For styling, the tags and the input sit side by side in a row that wraps. The border is on .tag-input, and :focus-within changes the border color only while the input inside has focus. .tag-input has an onClick handler that moves focus to the input when it is clicked. In the test environment, after I clicked outside the box to remove focus, clicking the empty area at the top-left of .tag-input, where there was no tag or input, moved focus to the input.
.tag-input {
display: flex;
flex-wrap: wrap;
gap: 6px;
padding: 6px;
border: 1px solid #9aa5ab;
border-radius: 6px;
}
.tag-input:focus-within {
border-color: #00c8e8;
outline: 2px solid #b8eef7;
}
.tags {
display: contents;
list-style: none;
}
.tag-input input {
flex: 1;
min-width: 8em;
border: 0;
outline: none;
}
With display: contents on .tags, the <ul> does not create its own box. Its <li> children are laid out as if they were direct children of .tag-input. As a result, the tags and the input share a row, and they wrap to the next line when there is not enough width. In the GIF at the top, the input moves to the second line once there are three tags. However, the MDN page on display says that some browsers remove an element with display: contents from the accessibility tree. The child elements remain, but according to the specification this behavior is incorrect. In such browsers, the <ul> may not be announced as a list.
Turn input into tags with Enter and ","
I typed several values into the input in the test environment. Here are the results.
「react」と入力して Enter: タグ ["react"] / 入力欄「」
「typescript」と入力して ,: タグ ["react","typescript"] / 入力欄「」
「React」と入力して Enter: タグ ["react","typescript"] / 入力欄「」
空白だけを入力して Enter: タグ ["react","typescript"] / 入力欄「」
「 vite 」と入力して Enter: タグ ["react","typescript","vite"] / 入力欄「」
"React" was not added, because "react" was already in the list and the two differ only in letter case. Input that was only spaces did not become a tag. " vite " with spaces on both sides became "vite" with the spaces removed. In every case, the input was empty after pressing Enter or ",".
The preventDefault() call on the "," key stops the comma itself from being typed into the input. I checked what happens without this call in a later section.
Do not create a tag from the Enter that confirms Japanese composition
When you type Japanese, you press Enter to confirm the conversion. That Enter also sends a keydown event. If nothing handles it, the Enter that was meant only to confirm the conversion creates a tag.
I reproduced the flow of typing the Japanese reading ねこ, converting it to 猫, and confirming with Enter. I compared a version of handleKeyDown that checks isComposing at the beginning with a version that does not.
isComposing を見る書き方(この記事の書き方)
届いた keydown: Enter(isComposing=true, keyCode=13)
「ねこ」を「猫」に変換して Enter で確定: タグ [] / 入力欄「猫」
もう一度 Enter: タグ ["猫"] / 入力欄「」
isComposing を見ない書き方
届いた keydown: Enter(isComposing=true, keyCode=13)
「ねこ」を「猫」に変換して Enter で確定: タグ ["猫"] / 入力欄「猫」
In this reproduction, the version that does not check isComposing created a tag 猫 from the Enter that confirmed the conversion. The confirmed 猫 also stayed in the input. In the version from this article, the confirming Enter did not create a tag, and 猫 stayed in the input. Pressing Enter again turned 猫 into a tag.
The React reference for KeyboardEvent does not list isComposing among the properties of React's event object. So the code reads it from e.nativeEvent, which is the original browser event. The MDN page on the keydown event shows a way to ignore keydown during composition by checking keyCode for 229 in addition to isComposing. The value 229 is a special code that browsers attach to key events handled by the IME. The same MDN section notes that if compositionend fires before keydown, a keydown with isComposing set to false and keyCode set to 229 can still arrive.
I could not run a real IME in the test environment. I reproduced composition and confirmation with the Chrome DevTools Protocol commands Input.imeSetComposition and Input.insertText. In this reproduction, the keyCode of the confirming Enter was 13, so the keyCode === 229 check did not match. The tag was not created because of the isComposing check. I have not verified the keyCode value sent by a real IME when it confirms text, or whether the text stays in the input in that case.
Remove the last tag with Backspace when the input is empty
In handleKeyDown, pressing Backspace when the input is empty removes the last tag. While the input still has text, Backspace deletes one character as usual.
「ab」と入力して Backspace: タグ ["react","typescript","vite"] / 入力欄「a」
もう一度 Backspace(入力欄が空になる): タグ ["react","typescript","vite"] / 入力欄「」
入力欄が空のときに Backspace: タグ ["react","typescript"] / 入力欄「」
When Backspace removed the last character and emptied the input, no tag was removed. The next Backspace removed the last tag, vite. The check text === '' looks at the input value at the time the key is pressed.
Name each delete button so it says which tag it removes
The × button next to each tag has an aria-label such as react を削除 (Remove react). The button content is only the single character "×", which does not say which tag it removes. The MDN page on aria-label shows an example of naming an icon-only button with aria-label. In testing, Playwright's getByRole('button', { name: 'react を削除' }) found the button and clicked it.
When a button is pressed, both the tag and the button disappear from the screen. This is why removeTag calls inputRef.current?.focus(). I compared this with a version that does not return focus.
フォーカスを戻さない書き方
「vite を削除」をクリック: タグ ["react"] / 入力欄「」 / フォーカス BODY
続けて「hooks」とキーを打つ: タグ ["react"] / 入力欄「」 / フォーカス BODY
この記事の書き方
「vite を削除」をクリック: タグ ["react"] / 入力欄「」 / フォーカス INPUT
続けて「hooks」とキーを打つ: タグ ["react"] / 入力欄「hooks」 / フォーカス INPUT
Without returning focus, focus moved to <body>, and the keys typed afterward went nowhere. A person using the keyboard would have to move focus back to the input manually.
Turn pasted text with separators into tags all at once
When you paste text that contains separators, such as 猫, 写真、 TypeScript, onPaste turns it into tags all at once. As described on the MDN page on the paste event, the pasted text can be read with clipboardData.getData(). Calling preventDefault() stops the usual behavior of inserting the pasted text into the input.
In the test environment, I continued from the Backspace test: I pressed the react を削除 button so that only typescript remained as a tag, and then pasted the following text.
「猫, 写真、 TypeScript\nhooks,,」を貼り付け: タグ ["typescript","猫","写真","hooks"] / 入力欄「」
区切りのない「useState」を貼り付け: タグ ["typescript","猫","写真","hooks"] / 入力欄「useState」
続けて Enter: タグ ["typescript","猫","写真","hooks","useState"] / 入力欄「」
The text was split at ",", "、", and the newline. "TypeScript" was not added because "typescript" was already in the list. The empty string between ",," was removed. The pasted text useState, which had no separator, went into the input as normal paste does, and pressing Enter turned it into a tag.
handlePaste does not look at the cursor position. It joins the pasted text to the end of the text in the input, and then splits the result. When I typed vtest into the input, placed the cursor after v, and pasted ite, hooks, the result was the tags vtestite and hooks. If the text had been inserted at the cursor position, the result would have been vite and hookstest.
splitTags also splits on "、", but only Enter and "," create tags from key presses. When I reproduced typing "、" with Japanese input after react, the "、" stayed in the input and did not become a tag. After I typed vite so that the input contained react、vite, pressing Enter created two tags, react and vite.
When sending with a form, put the tags in hidden inputs
This shows how to send the tag input together with other inputs in a form. The tags are in the state array, not in an <input>'s value, so they are not included in the form values automatically. In the parent component, render each tag as its own type="hidden"
<input>. Then FormData can read them.
import { useState } from 'react';
import { TagInput } from './TagInput';
export function App() {
const [tags, setTags] = useState<string[]>([]);
const [sent, setSent] = useState('');
function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const data = new FormData(e.currentTarget);
setSent(JSON.stringify(data.getAll('tags')));
}
return (
<form onSubmit={handleSubmit}>
<TagInput label="タグ" tags={tags} onChange={setTags} />
{/* Put each tag in its own hidden input so it is sent as a form value */}
{tags.map((tag) => (
<input key={tag} type="hidden" name="tags" value={tag} />
))}
<p className="count">{tags.length}個のタグ</p>
<button type="submit">保存</button>
<output>{sent}</output>
</form>
);
}
With the five tags from the previous section displayed, I pressed the 保存 (Save) button. data.getAll('tags') returned ["typescript","猫","写真","hooks","useState"]. Values with the same name come back in the order the tags are displayed.
Without preventDefault, Enter submits the form
I also tested a version of handleKeyDown without the e.preventDefault() call.
「react」と入力して Enter: タグ ["react"] / 入力欄「」 / 送信 1回
「vite」と入力して ,: タグ ["react","vite"] / 入力欄「,」 / 送信 1回
When I pressed Enter, the tag was added, and the form's submit event fired at the same time. When I pressed ",", the tag was added, but the "," stayed in the input, which should have been empty. In the version from this article, pressing Enter fired no submit events.
The HTML specification section on implicit submission describes the behavior where pressing Enter in a text input inside a form submits the form. Enter is used to create a tag here, so the keydown handler must call preventDefault(). Otherwise, a form the user is still filling in would be submitted.





