Command palette

@yasinsensoy/web

Web · Components

TagInput

Tag input: turns typed text into tags with Enter or a comma.

10 exports

Live example

Preview

  • React
  • TypeScript

Try pasting from Excel or a comma-separated list, and ← and Backspace in the empty field.

Code

import { TagField } from "@yasinsensoy/web";

<TagField label="Skills" name="tag" max={8} maxLength={24} placeholder="Type, add with Enter or a comma" required
  items={["React", "Next.js", …]} />

Events

  1. Events appear here when you interact with the preview.

Email recipients: split by space/comma/semicolon, validate

Hashtag: # is removed, only letters/digits/dashes, color by tag

  • #urgent
  • #design
  • #frontend

Team members: from the list only, search on the server

Read only

  • Turkish
  • English
  • Deutsch

Import

import { TagInput, splitTags, sameTag, checkTag } from "@yasinsensoy/web";

TagInput

componentClient component

Tag input: turns typed text into tags with Enter or a comma. For multiple free values like tags, email recipients, keywords, skill lists.

  • Fast entry: Enter, comma (or separators) complete a tag; pasting "a, b, c" or rows from Excel adds them all at once. Works on Android keyboards too (it looks at the text, not the key).
  • Validation: max, maxLength, pattern, validate, duplicate check. Text that can't be added stays in the box with the reason below; a tag added again is shown with a short highlight.
  • Suggestions: With items/loadItems, the list of Autocomplete (virtualization, server search, highlighted matches); added ones don't appear in the list. allowCustomValue={false} allows only suggestions.
  • Editing: Double-click a tag or press Enter to fix it in place.
  • Keyboard: In an empty box ← moves to the last tag; ←/→ between tags, Backspace/Delete remove. In an empty box Backspace first selects the last tag, a second press removes it (no accidental deletion).
  • Form: With name each tag is submitted separately (getAll), required works, it resets with the form. For label, description and error see TagField.
TagInput(props: TagInputProps): JSX.Element

Examples

<TagInput name="tags" placeholder="Add tag" />

<TagInput name="skills" items={["React", "Next.js", "Tailwind"]} max={5} />

<TagInput name="recipients" separators={[",", ";", " "]} placeholder="Email"
  validate={(tag) => /^\S+@\S+\.\S+$/.test(tag) || "Enter a valid email"} />

<TagInput name="people" allowCustomValue={false}
  loadItems={({ query, signal }) => searchPeople(query, signal)} />

splitTags

function

Splits text at separators. Line breaks and tabs are always separators (pasting from Excel or a list). Empty pieces are dropped and edges trimmed.

splitTags(text: string, separators?: readonly string[]): string[]

Examples

`splitTags("react, next\nvite", [","])` → `["react", "next", "vite"]`

sameTag

function

Are two tags the same? Case, Turkish character and accent differences are ignored.

sameTag(a: string, b: string): boolean

checkTag

function

Tells whether a tag can be added. index is the index of the already added tag for a "duplicate" result.

checkTag(tag: string, tags: readonly string[], rules: TagRules): TagCheck

Examples

checkTag("React", ["react"], {}) // { ok: false, reason: "duplicate", index: 0 }
checkTag("a b", [], { pattern: /^\S+$/ }) // { ok: false, reason: "invalid" }

Classes that can be passed to the inner parts of TagInput.

NameTypeDescription
control?stringFrame wrapping the tags and the text field.
input?stringText field.
tag?stringEach tag.
message?stringRow stating why a tag couldn't be added.
content?stringPanel where suggestions open.
item?stringEach suggestion.

TagInputProps

interface

Props of the TagInput component.

NameTypeDefaultDescription
variant?FieldVariant | CustomVariant<"field">Look: outline (bordered), filled, underline or ghost (plain). If omitted, the setting of the nearest data-field-variant container is used, otherwise outline. See FieldVariant.
effect?EffectPropEffect or effects of the field box (e.g. "glow", ["lift", "beam"]). The accent color is the focus color (--ui-field-focus). If omitted, UIProvider appearance.defaults.field.effect. See BuiltinEffect.
value?readonly string[]Tags in controlled use.
defaultValue?readonly string[]Initial tags in uncontrolled use.
onValueChange?(tags: string[]) => voidCalled when tags change (add, remove, edit, clear).
onTagAdd?(tag: string, item: SelectItem | undefined) => voidCalled when a tag is added (with its item if picked from suggestions).
onTagRemove?(tag: string) => voidCalled when a tag is removed.
onReject?(text: string, reason: TagRejectReason, message: string) => voidCalled when a text can't be added as a tag. The message is already shown below the box; this is for your own notification or metrics.
items?SelectItemsSourceSuggestions: an array, a Promise or a function called once. Filtered while typing; added tags don't appear in the list. Same format as Select.
loadItems?SelectLoaderFunction that searches suggestions on the server. See Select loadItems.
allowCustomValue?booleantrueWhether text not in the suggestions can also become a tag. When off, only suggestions can be picked (e.g. registered users). Always on without suggestions.
separators?readonly string[][","]Separators that complete a tag while typing. Enter always completes; when pasting, line breaks and tabs are separators too. To separate by space, [",", " "].
max?numberMaximum number of tags; if given, a 3/10 counter shows in the box.
maxLength?numberMaximum number of characters in a tag.
pattern?RegExpPattern the whole tag must match (e.g. /^[a-z0-9-]+$/).
validate?TagValidatorExtra validation: return false or the message to show if invalid.
transform?(text: string) => stringTransforms the text before adding (e.g. lowercase, removing #). Surrounding whitespace is already trimmed.
allowDuplicates?booleanfalseWhether the same tag can be added several times. When off (ignoring case and locale-specific character differences), a tag added again is shown with a short highlight.
addOnBlur?booleantrueWhether typed text becomes a tag on blur.
editable?booleantrueWhether tags can be edited in place on double-click (Enter/F2 on the keyboard).
tone?Tone | ((tag: string) => Tone)"neutral"Color of the tags; a function for per-tag color ((tag) => tag === "urgent" ? "danger" : "neutral").
renderTag?(tag: string, item: SelectItem | undefined) => ReactNodeDraw the tag content yourself (e.g. avatar + name). The remove button and keyboard behavior are kept.
inputValue?stringText in the text field in controlled use.
onInputChange?(text: string) => voidCalled when the text in the text field changes.
placeholder?stringText shown while the box is empty.
emptyMessage?ReactNodeContent shown when no suggestion is found.
icon?IconPropIcon at the start of the box (e.g. "tag").
clearable?booleantrue× button clearing all tags.
name?stringForm field name; each tag is submitted separately under this name (formData.getAll(name)).
form?stringId of the form the field belongs to (if outside the form).
required?booleanThe form can't be submitted without at least one tag.
disabled?booleanDisabled.
readOnly?booleanTags are visible but can't be added or removed.
id?stringId of the text field; <Label htmlFor> links to it.
autoFocus?booleanFocuses when the page opens.
tooltip?TooltipPropTooltip shown when hovering the box. See TooltipProp.
className?stringClasses added to the container.
classNames?TagInputClassNamesClasses added to the inner parts.
aria-label?stringScreen reader name if there is no visible label.
aria-labelledby?stringId of the element naming the box.
aria-describedby?stringId of the element describing the box. TagField passes it itself.
aria-invalid?boolean | "true" | "false"Show the field as invalid. TagField passes it itself.

Why a tag wasn't added.

type TagRejectReason = /** The same tag is already added (case and Turkish character differences are ignored). */ "duplicate" /** The `max` limit was reached. */ | "limit" /** Longer than `maxLength`. */ | "tooLong" /** Doesn't match the `pattern` or `validate` rule. */ | "invalid" /** Not among the suggestions while `allowCustomValue={false}`. */ | "notInList"

Tag validator. Returns true (or nothing) when valid, false or an error message to show when invalid.

type TagValidator = (tag: string, tags: readonly string[]) => boolean | string | null | undefined

Examples

`(tag) => tag.includes("@") || "Enter a valid email"`

TagRules

interface

Options of splitTags and checkTag.

NameTypeDescription
separators?readonly string[]Separators; split text into tags while typing or pasting.
max?number | undefinedTag count limit.
maxLength?number | undefinedMaximum characters of a tag.
pattern?RegExp | undefinedPattern the whole tag must match (e.g. /^[a-z0-9-]+$/).
validate?TagValidator | undefinedExtra validation. See TagValidator.
allowDuplicates?boolean | undefinedCan the same tag be added more than once?

Result of checkTag.

NameTypeDescription
oktrue | falseThe tag can be added.
reasonTagRejectReasonRejection reason.({ /** The tag cannot be added. */ ok: false; /** Rejection reason. */ reason: TagRejectReason; /** Error text returned by the `validate` rule. */ message?: string; /** Index of the already added tag for a `"duplicate"` result. */ index?: number; })
message?stringError text returned by the validate rule.({ /** The tag cannot be added. */ ok: false; /** Rejection reason. */ reason: TagRejectReason; /** Error text returned by the `validate` rule. */ message?: string; /** Index of the already added tag for a `"duplicate"` result. */ index?: number; })
index?numberIndex of the already added tag for a "duplicate" result.({ /** The tag cannot be added. */ ok: false; /** Rejection reason. */ reason: TagRejectReason; /** Error text returned by the `validate` rule. */ message?: string; /** Index of the already added tag for a `"duplicate"` result. */ index?: number; })