@molecule/app-tag-input-react
Feature · tag-input · App (browser) · v5.0.1 · Apache-2.0
React tags/labels/keywords input — a tag-token (chip) input, a markup-free useTagInput hook for app-owned markup, and tag-chip display
npm install @molecule/app-tag-input-reactHow it works
@molecule/app-tag-input-react is a ready-made tag-input feature for the app (browser) side. It composes the core interfaces it needs, so it works with whichever providers your app has bonded.
import { useState } from 'react'
import { useTranslation } from '@molecule/app-react'
import { TagChip, TagInput, TagList, useTagInput } from '@molecule/app-tag-input-react'
function TagEditor() {
const [tags, setTags] = useState<string[]>(['react'])
return (
<>
<TagInput value={tags} onChange={setTags} maxTags={10} />
<TagChip onRemove={() => setTags(tags.filter((t) => t !== 'react'))}>react</TagChip>
</>
)
}
// Render the saved record's tags on the destination screen as well as in its editor.
function RecordLabels({ record }: { record: { labels: string[] } }) {
return <TagList value={record.labels} />
}
// App-owned markup: the input and the tag list are siblings.
function ArticleTags({ tags, setTags }: { tags: string[]; setTags: (t: string[]) => void }) {
const { t } = useTranslation()
const { inputProps, remove } = useTagInput({ value: tags, onChange: setTags })
return (
<>
<input {...inputProps} />
<ul>
{tags.map((tag, i) => (
<li key={tag}>
<button type="button" onClick={() => remove(i)}>
{t('tagChip.remove', {}, { defaultValue: 'Remove' })}
</button>{' '}
{tag}
</li>
))}
</ul>
</>
)
}Works with: @molecule/app-react, @molecule/app-ui, @molecule/app-ui-react
Reference
React tag-token input and tag-chip display.
Exports:
<TagList>— read-only saved tags on detail/preview screens. Renders every value in order. Pass Box props,itemClassName, andrenderTagto use the same component in the preview and the destination page's markup.<TagChip>— standalone labeled chip with optional remove button.<TagInput>— controlled tokenizer: Enter, comma, or Tab adds the draft; blur commits a non-empty draft; Backspace on an empty field removes the last token. Enter never submits an enclosing form.useTagInput()— the same tag-entry behavior without markup, for an app whose markup is already decided (a design system, a spec's selectors): spreadfieldPropson aTextFieldorinputPropson your own<input>, render the tags yourself, and callremove(i)from your own remove control.
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Quick Start
import { useState } from 'react'
import { useTranslation } from '@molecule/app-react'
import { TagChip, TagInput, TagList, useTagInput } from '@molecule/app-tag-input-react'
function TagEditor() {
const [tags, setTags] = useState<string[]>(['react'])
return (
<>
<TagInput value={tags} onChange={setTags} maxTags={10} />
<TagChip onRemove={() => setTags(tags.filter((t) => t !== 'react'))}>react</TagChip>
</>
)
}
// Render the saved record's tags on the destination screen as well as in its editor.
function RecordLabels({ record }: { record: { labels: string[] } }) {
return <TagList value={record.labels} />
}
// App-owned markup: the input and the tag list are siblings.
function ArticleTags({ tags, setTags }: { tags: string[]; setTags: (t: string[]) => void }) {
const { t } = useTranslation()
const { inputProps, remove } = useTagInput({ value: tags, onChange: setTags })
return (
<>
<input {...inputProps} />
<ul>
{tags.map((tag, i) => (
<li key={tag}>
<button type="button" onClick={() => remove(i)}>
{t('tagChip.remove', {}, { defaultValue: 'Remove' })}
</button>{' '}
{tag}
</li>
))}
</ul>
</>
)
}
Type
feature
Installation
npm install @molecule/app-tag-input-react @molecule/app-react @molecule/app-ui @molecule/app-ui-react react
npm install -D @types/react
API
Interfaces
TagChipProps
Props for the TagChip component.
interface TagChipProps {
/** Visible tag text. */
children: ReactNode
/** Optional remove callback — renders an `×` button when provided. */
onRemove?: () => void
/**
* Optional click callback for the chip body. Fired by mouse click and, for
* keyboard users, by Enter / Space on the focused chip body. When
* `onRemove` is also set, the body action moves onto a native button
* around the label text (a chip holding two controls cannot itself be a
* button), so mouse users click the same label surface as before.
*/
onClick?: () => void
/** Extra classes. */
className?: string
}
TagInputProps
Props for the TagInput component.
interface TagInputProps {
/** Controlled list of tag values. */
value: string[]
/** Called whenever the tag list changes. */
onChange: (next: string[]) => void
/** Placeholder shown in the text input when no tokens exist yet. */
placeholder?: string
/**
* Validate/transform an input before adding. Return `null` to reject.
* Default trims whitespace and rejects empty + duplicate entries.
*/
normalize?: (raw: string, current: string[]) => string | null
/** Max tags allowed. When reached, further input is ignored. */
maxTags?: number
/** Extra classes on the outer wrapper. */
className?: string
}
TagListProps
Read-only tags from the saved record, with optional app-owned tag markup.
interface TagListProps extends ForwardedElementProps<
BoxProps<ReactNode>,
'children' | 'className'
> {
/** Every saved tag, in display order. Empty arrays render an empty list. */
value: readonly string[]
/** Additional classes on the list. */
className?: string
/** Additional classes for each list item. */
itemClassName?: string
/** Optional tag content; the component still renders every value. */
renderTag?: (tag: string, index: number) => ReactNode
}
UseTagInputOptions
Options for useTagInput.
interface UseTagInputOptions {
/** Controlled list of tag values. */
value: string[]
/** Called whenever the tag list changes. */
onChange: (next: string[]) => void
/**
* Validate/transform an input before adding. Return `null` to reject.
* Default trims whitespace and rejects empty + duplicate entries.
*/
normalize?: (raw: string, current: string[]) => string | null
/** Max tags allowed. When reached, further input is ignored. */
maxTags?: number
}
TagInputFieldProps
Props to spread onto the text <input> that types new tags.
interface TagInputFieldProps {
/** The draft text. */
value: string
/** Updates the draft. */
onChange: (e: ChangeEvent<HTMLInputElement>) => void
/** Enter/comma/Tab commit the draft; Backspace on an empty draft removes the last tag. */
onKeyDown: (e: KeyboardEvent<HTMLInputElement>) => void
/** Commits a non-empty draft when the field loses focus. */
onBlur: () => void
}
UseTagInputResult
What useTagInput returns.
interface UseTagInputResult {
/** The current draft text. */
draft: string
/** Replaces the draft text. */
setDraft: (next: string) => void
/** Spread onto your own `<input>`: `<input {...inputProps} placeholder={placeholder} />`. */
inputProps: TagInputFieldProps
/** Read directly or destructure for a `<TextField as="input">` on web or device. */
readonly fieldProps: TagInputTextFieldProps
/** Normalizes and adds a tag without clearing the draft; returns whether it was added. */
add: (raw: string) => boolean
/** Removes the tag at `index`. */
remove: (index: number) => void
}
Types
TagInputTextFieldProps
The props to spread onto a renderer-neutral TextField.
type TagInputTextFieldProps = Required<
Pick<TextFieldProps, 'value' | 'onValueChange' | 'onKeyDown' | 'onBlur'>
>
Functions
TagChip(props)
Small labeled chip with an optional close button. Used inside
<TagInput> but also usable standalone as a label display element.
The chip body action is keyboard-operable. With no remove button the chip
itself is the control: role="button", tabbable, and Enter / Space fire
onClick. With a remove button the action lives on a native button
around the label text instead, since a button may not contain another
control — the native button carries its own Enter / Space activation.
function TagChip({ children, onRemove, onClick, className }: TagChipProps): JSX.Element
props— Component props (seeTagChipProps).
TagInput(props)
Tokenized tag-input with chip display. Commits the draft on Enter, comma, or Tab AND on blur (clicking away with a non-empty draft adds a tag); Backspace on an empty field removes the last token.
Enter never submits an enclosing form: its default action is canceled
even when the draft is blank, whitespace-only, rejected, or past
maxTags. An empty Tab keeps normal browser focus traversal.
Controlled component — callers own the value array. For markup the
app already decided (a design system, a spec's selectors), use
useTagInput directly: this component is that hook plus default markup.
function TagInput({
value,
onChange,
placeholder,
normalize,
maxTags,
className,
}: TagInputProps): JSX.Element
props— Component props (seeTagInputProps).
TagList(props)
Display all saved tags on a detail or preview screen, without an editor or remove controls. The component owns iteration. List attributes such as id and aria-label go on the list itself.
function TagList({
value,
className,
itemClassName,
renderTag,
...listProps
}: TagListProps): JSX.Element
props— Saved values and optional presentation.
Returns: A semantic list with one item per saved tag.
useTagInput(options)
Tag-entry behavior without markup, for an app whose markup is already
decided (a design system, a spec's selectors). Spread inputProps onto
your own <input> and render the tags however you need, calling
remove(i) from your own remove control. <TagInput> is this hook plus
default markup.
Enter commits the draft and never submits an enclosing form: its default
is canceled even when the draft is blank, rejected, or past maxTags.
Comma and Tab commit a non-empty draft (an empty Tab keeps normal focus
traversal); blur commits a non-empty draft; Backspace on an empty draft
removes the last tag.
function useTagInput({
value,
onChange,
normalize = defaultNormalize,
maxTags,
}: UseTagInputOptions): UseTagInputResult
options— The controlled tag list and its rules (seeUseTagInputOptions).
Returns: The draft, input props and add/remove actions (see UseTagInputResult).
Injection Notes
Requirements
Peer dependencies:
@molecule/app-react^4.9.0 || ^5.0.0@molecule/app-ui^1.9.0@molecule/app-ui-react^4.7.0react^18.0.0 || ^19.0.0
Runtime Dependencies
-
@molecule/app-react -
@molecule/app-ui -
@molecule/app-ui-react -
react -
<TagInput>and<TagChip>need the app's i18n provider and a ClassMap bond wired (useTranslation()/getClassMap()throw otherwise).useTagInputitself needs neither; the app owns its markup and text. -
add(raw)adds an independent value without changing the draft (for example, a suggestion). A custom draft-commit control should calladd(draft)followed bysetDraft('')to avoid a later blur reusing it. Actions compose within one React batch and reconcile to the controlledvalueon the next commit. -
Committing happens on Enter/comma/Tab AND on blur — clicking away with a non-empty draft adds a tag; keep that in mind in forms.
-
Enter inside the field is always swallowed: a blank, rejected, or over-
maxTagsdraft does nothing and never submits an enclosing form. An empty Tab keeps normal browser focus traversal. -
Default
normalizetrims whitespace and rejects empties + duplicates; pass your own to lowercase, validate, or map values (returnnullto reject). -
When
maxTagsis reached further input is silently discarded (the draft clears, no error UI). -
<TagChip>ships no background surface of its own — add one viaclassNameif bare text chips are too subtle in your theme.
Translations
Translation strings are provided by @molecule/app-locales-tag-input.