Components
Tag Field
A field for a list of short values, each one shown as a removable tag. Built on react-aria-components.
Introduction
Tag Field collects a list of short values: keywords, email addresses, labels. The user types a value and confirms it, and it becomes a tag they can see and remove. The value in your code is a plain array of strings.
- Press Enter or type a comma to add a tag. Text still in the input becomes a tag when the field loses focus.
- Pasting text with commas or line breaks adds one tag for each piece. Duplicates are ignored.
- Backspace in the empty input removes the last tag, every tag has its own remove button, and the arrow keys walk through the tags.
- Limit the count with
maxTagsand accept only some values withvalidateTag. - Works in a form: give it a
nameand every tag is submitted under it.
To choose from a fixed list, use Select or Autocomplete. Tag Field is for values the user makes up.
Installation
centerUI has no CLI or registry yet: components are copied into your project.
# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx
# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx
# npm
npm install react-aria-components tailwind-variants tailwind-merge clsxManual installation
Copy these files into your project and keep the paths, or adjust the imports.
1. Add the styles
src/types/tag-field-styles.tsShow code
import { tv } from "tailwind-variants";
// The frame holds the tags and the input, side by side, and wraps onto more
// lines when there are many tags. The focus ring wraps all of it.
export const tagFieldStyles = tv({
slots: {
frame: [
"flex w-full flex-wrap items-center rounded-md text-fg transition-colors",
"focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-bg",
"group-data-invalid/tag-field:border-danger",
"group-data-disabled/tag-field:pointer-events-none group-data-disabled/tag-field:opacity-50",
],
tag: [
"inline-flex cursor-default items-center gap-1 rounded-[5px] pr-1 pl-2 font-medium outline-none transition-colors",
"data-focus-visible:ring-2 data-focus-visible:ring-ring",
],
remove: [
"flex shrink-0 cursor-pointer items-center justify-center rounded-[4px] text-muted-fg outline-none transition-colors",
"data-hovered:bg-fg/10 data-hovered:text-fg data-pressed:bg-fg/20",
"[&_svg]:size-3",
],
input:
"h-full min-w-20 flex-1 bg-transparent px-1 outline-none placeholder:text-muted-fg read-only:cursor-default",
},
variants: {
variant: {
outline: {
frame: "border bg-transparent",
tag: "bg-secondary text-secondary-fg",
},
secondary: {
frame: "bg-secondary text-secondary-fg",
tag: "bg-bg text-fg",
},
ghost: {
frame: "bg-transparent focus-within:bg-muted hover:bg-muted",
tag: "bg-secondary text-secondary-fg",
},
},
size: {
sm: {
frame: "min-h-8 gap-1 p-[5px] text-sm",
tag: "h-5 text-xs",
remove: "size-4",
input: "h-5",
},
md: {
frame: "min-h-9 gap-1.5 p-[5px] text-sm",
tag: "h-6 text-sm",
remove: "size-4",
input: "h-6",
},
lg: {
frame: "min-h-11 gap-1.5 p-[7px] text-base",
tag: "h-7 text-sm",
remove: "size-5",
input: "h-7",
},
},
},
defaultVariants: { variant: "outline", size: "md" },
});2. Add the Tag Field file
src/components/ui/tag-field/tag-field.tsxShow code
"use client";
import { type ReactNode, useRef, useState } from "react";
import {
Button as AriaButton,
TextField as AriaTextField,
FieldError,
Input,
Label,
Tag,
TagGroup,
TagList,
Text,
type ValidationResult,
} from "react-aria-components";
import { XIcon } from "@/components/icons";
import { cn } from "@/lib/cn";
import { tagFieldStyles } from "@/types/tag-field-styles";
export interface TagFieldProps {
label?: ReactNode;
/** Help text under the field. */
description?: ReactNode;
/** Shown when the field is invalid. A function receives the validation result. */
errorMessage?: string | ((validation: ValidationResult) => string);
/** Shown while there are no tags. */
placeholder?: string;
/** The tags, for a controlled field. */
value?: string[];
/** The tags to start with, for an uncontrolled field. */
defaultValue?: string[];
onChange?: (tags: string[]) => void;
/** The most tags that can be added. Further text is ignored. */
maxTags?: number;
/**
* Decide whether a tag may be added, for example to accept only email
* addresses. A tag that fails stays in the input, and `onReject` is called.
*/
validateTag?: (tag: string) => boolean;
/** Called with the tags that `validateTag` refused. */
onReject?: (tags: string[]) => void;
/** Turn the text that is still in the input into a tag when the field loses focus. Defaults to `true`. */
addOnBlur?: boolean;
/** Look of the field. */
variant?: "outline" | "secondary" | "ghost";
/** Size of the field. */
size?: "sm" | "md" | "lg";
/** Each tag is submitted with a form under this name. */
name?: string;
autoFocus?: boolean;
isDisabled?: boolean;
isReadOnly?: boolean;
isInvalid?: boolean;
isRequired?: boolean;
"aria-label"?: string;
className?: string;
}
/**
* A field for a list of short values: keywords, email addresses, labels. Type
* a value and press Enter or a comma to turn it into a tag. Backspace in the
* empty input removes the last tag, and every tag has a button to remove it.
* Pasting text with commas or line breaks adds one tag per piece.
*
* The tags are a react-aria TagGroup, so the arrow keys move between them and
* Delete removes the focused one. The label, description and error come from a
* react-aria TextField. The value is an array of strings, and every tag is
* unique.
*
* @example
* <TagField label="Keywords" defaultValue={["react"]} onChange={setTags} />
*/
export function TagField({
label,
description,
errorMessage,
placeholder,
value,
defaultValue,
onChange,
maxTags,
validateTag,
onReject,
addOnBlur = true,
variant,
size = "md",
name,
autoFocus,
isDisabled,
isReadOnly,
isInvalid,
isRequired,
className,
...props
}: TagFieldProps) {
const styles = tagFieldStyles({ variant, size });
const inputRef = useRef<HTMLInputElement>(null);
const frameRef = useRef<HTMLDivElement>(null);
const [text, setText] = useState("");
const isControlled = value !== undefined;
const [inner, setInner] = useState(defaultValue ?? []);
const tags = isControlled ? value : inner;
function setTags(next: string[]) {
if (!isControlled) setInner(next);
onChange?.(next);
}
// Turns raw text into tags: split at commas and line breaks, trimmed, with
// duplicates, refused and over-the-limit pieces left out. Returns what stays
// in the input, which is only the refused pieces.
function commit(raw: string) {
const pieces = raw
.split(/[,\n]/)
.map((piece) => piece.trim())
.filter(Boolean);
if (pieces.length === 0) return "";
const next = [...tags];
const refused: string[] = [];
for (const piece of pieces) {
if (next.includes(piece)) continue;
if (maxTags !== undefined && next.length >= maxTags) break;
if (validateTag && !validateTag(piece)) {
refused.push(piece);
continue;
}
next.push(piece);
}
if (next.length !== tags.length) setTags(next);
if (refused.length > 0) onReject?.(refused);
return refused.join(", ");
}
const canEdit = !isDisabled && !isReadOnly;
const fieldName = typeof label === "string" ? label : props["aria-label"];
return (
<AriaTextField
value={text}
onChange={(raw) => setText(/[,\n]/.test(raw) ? commit(raw) : raw)}
aria-label={props["aria-label"]}
isDisabled={isDisabled}
isReadOnly={isReadOnly}
isInvalid={isInvalid}
isRequired={isRequired && tags.length === 0}
autoFocus={autoFocus}
className={cn("group/tag-field flex w-full flex-col gap-1.5", className)}
>
{label ? (
<Label className="text-sm font-medium group-data-required/tag-field:after:ml-0.5 group-data-required/tag-field:after:text-danger group-data-required/tag-field:after:content-['*']">
{label}
</Label>
) : null}
{/* Clicking the empty space of the frame focuses the input. */}
{/* biome-ignore lint/a11y/noStaticElementInteractions: a mouse shortcut, the input is still reachable by keyboard */}
<div
ref={frameRef}
className={styles.frame()}
onMouseDown={(event) => {
if (event.target !== event.currentTarget) return;
event.preventDefault();
inputRef.current?.focus();
}}
>
<TagGroup
aria-label={fieldName ? `${fieldName} tags` : "Tags"}
className="contents"
onRemove={
canEdit
? (keys) => {
setTags(tags.filter((tag) => !keys.has(tag)));
inputRef.current?.focus();
}
: undefined
}
>
<TagList className="contents">
{tags.map((tag) => (
<Tag key={tag} id={tag} textValue={tag} className={styles.tag()}>
{({ allowsRemoving }) => (
<>
<span className="truncate">{tag}</span>
{allowsRemoving ? (
<AriaButton
slot="remove"
aria-label={`Remove ${tag}`}
className={styles.remove()}
>
<XIcon />
</AriaButton>
) : (
<span className="w-1" />
)}
</>
)}
</Tag>
))}
</TagList>
</TagGroup>
<Input
ref={inputRef}
placeholder={tags.length === 0 ? placeholder : undefined}
className={styles.input()}
onKeyDown={(event) => {
if (event.key === "Enter" && text.trim() !== "") {
// Adding a tag must not also submit the form around the field.
event.preventDefault();
setText(commit(text));
} else if (event.key === "Backspace" && text === "" && canEdit) {
if (tags.length > 0) setTags(tags.slice(0, -1));
} else if (
event.key === "ArrowLeft" &&
event.currentTarget.selectionStart === 0 &&
event.currentTarget.selectionEnd === 0
) {
// Move to the last tag, so the arrow keys can walk through them.
const rows =
frameRef.current?.querySelectorAll<HTMLElement>('[role="row"]');
rows?.[rows.length - 1]?.focus();
}
}}
// A single-line input drops line breaks from what is pasted, so a
// pasted list is split here instead.
onPaste={(event) => {
const pasted = event.clipboardData.getData("text");
if (!canEdit || !/[,\n]/.test(pasted)) return;
event.preventDefault();
setText(commit(text + pasted));
}}
onBlur={() => {
if (addOnBlur && canEdit && text.trim() !== "") {
setText(commit(text));
}
}}
/>
</div>
{name
? tags.map((tag) => (
<input key={tag} type="hidden" name={name} value={tag} />
))
: null}
{description ? (
<Text slot="description" className="text-sm text-muted-fg">
{description}
</Text>
) : null}
<FieldError className="text-sm text-danger">{errorMessage}</FieldError>
</AriaTextField>
);
}It imports XIcon from @/components/icons for the remove button. Add that icon, or swap it for your own.
3. Use it
import { TagField } from "@/components/ui/tag-field/tag-field";Anatomy
A tag field is a frame with the tags and the input side by side.
<TagField
label="Keywords"
description="Press Enter or a comma after each one."
placeholder="Add a keyword"
defaultValue={["react", "css"]}
/>| Part | Rendered as | Notes |
|---|---|---|
| Label | label | Names the field. Clicking it focuses the input. |
| Tags | TagGroup | One chip per value, each with a button that removes it. The arrow keys move between them. |
| Input | input | Where the next tag is typed. It sits after the last tag, and the row wraps when it is full. |
| Description / error | text under the field | Help text, replaced by the error message when the field is invalid. |
Without a label, give the field an aria-label so a screen reader can name it.
Examples
Type a value and press Enter or a comma.
Usage
Label
Every field needs a name. Use label, or aria-label when the label is written elsewhere.
Description
Help text under the field.
Uncontrolled
Let the field keep its own tags. Start with defaultValue, and give it a name to read them from a form.
Controlled
Keep the tags in your own state with value and onChange, so you can read, replace or clear them from outside.
value: [react, css]
In a form
With a name, every tag is submitted as its own entry with that name. Pressing Enter to add a tag does not submit the form.
Read only
The tags can be seen and copied, but not added or removed.
Sizes
Variants
Disabled
Validation
Set isInvalid with an errorMessage. The field gets a red border and the message shows under it.
Component API
Tag Field takes the props below.
| Prop | Type | Default |
|---|---|---|
| label | ReactNode | - |
| description | ReactNode | - |
| errorMessage | string | (validation) => string | - |
| placeholder | string | - |
| value | string[] | - |
| defaultValue | string[] | [] |
| onChange | (tags: string[]) => void | - |
| maxTags | number | - |
| validateTag | (tag: string) => boolean | - |
| onReject | (tags: string[]) => void | - |
| addOnBlur | boolean | true |
| name | string | - |
| variant | "outline" | "secondary" | "ghost" | "outline" |
| size | "sm" | "md" | "lg" | "md" |
| autoFocus | boolean | false |
| isDisabled | boolean | false |
| isReadOnly | boolean | false |
| isInvalid | boolean | false |
| isRequired | boolean | false |
| aria-label | string | - (when there is no label) |