Tags Input
Free-form tags field: commits on submit or delimiter (paste splits), rejects duplicates, removable chips, backspace removes the last tag, controlled refusal.
Install
First install? Set up the registry in your app.
npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add tags-inputSource files
Expand a file to read the source the installer copies into your app.
components/ui/tags-input/TagsInput.tsx
import * as React from 'react'
import { View, type TextInput } from 'react-native'
import { Chip } from '@/components/ui/chip'
import { Input, type InputProps } from '@/components/ui/input'
import { cn } from '@/lib/utils'
export interface TagsInputProps extends Omit<
InputProps,
'value' | 'defaultValue' | 'onChangeText' | 'editable' | 'submitBehavior'
> {
/** Controlled tags. The owner may refuse a change by not applying it. */
value?: string[]
defaultValue?: string[]
onValueChange?: (tags: string[]) => void
/** Characters that commit the draft. A newline always commits too (multi-line paste). Default `[',']`. */
delimiters?: string[]
disabled?: boolean
/** Classes for the outer wrapper that holds the tag list and the field. */
wrapperClassName?: string
}
const key = (tag: string) => tag.toLocaleLowerCase()
/** Splits on delimiters and newlines. While typing, the last segment is the unfinished draft. */
const segments = (text: string, delimiters: string[]) =>
delimiters.reduce((acc, d) => acc.split(d).join('\n'), text).split('\n')
/** New tags from `candidates`: trimmed, non-empty, and unique case-insensitively against `existing` and each other. */
function newTags(existing: string[], candidates: string[]) {
const seen = new Set(existing.map(key))
return candidates.map((tag) => tag.trim()).filter((tag) => tag && !seen.has(key(tag)) && seen.add(key(tag)))
}
/**
* Free-form tags field. Draft rules:
* - A commit that adds tags clears the draft (keeping any text typed after the last delimiter)
* once the tags are actually rendered. If a controlled owner refuses, the draft keeps the text exactly
* as typed, delimiter included, so nothing the user typed is lost.
* - A commit with only empty or duplicate (case-insensitive) segments adds nothing and clears them:
* the tag is already visible.
*/
export const TagsInput = React.forwardRef<React.ComponentRef<typeof TextInput>, TagsInputProps>(
(
{
value,
defaultValue,
onValueChange,
delimiters = [','],
disabled = false,
wrapperClassName,
onKeyPress,
onSubmitEditing,
...props
},
ref,
) => {
const [internal, setInternal] = React.useState(defaultValue ?? [])
const tags = value ?? internal
const [draft, setDraft] = React.useState('')
// Tags awaiting the owner, plus the draft to show once they render.
const pending = React.useRef<{ added: string[]; tail: string } | null>(null)
// Layout effect: the typed text is swapped for the tail before paint, so a commit never flashes.
React.useLayoutEffect(() => {
const wait = pending.current
if (!wait) return
pending.current = null
const rendered = new Set(tags.map(key))
if (wait.added.every((tag) => rendered.has(key(tag)))) setDraft(wait.tail)
}, [tags])
const change = (next: string[]) => {
if (value === undefined) setInternal(next)
onValueChange?.(next)
}
const commit = (candidates: string[], tail: string, typed: string) => {
const added = newTags(tags, candidates)
if (!added.length) return setDraft(tail)
pending.current = { added, tail }
// Shown until the tags render; stays if a controlled owner refuses.
setDraft(typed)
change([...tags, ...added])
}
const remove = (index: number) => {
if (disabled) return
pending.current = null
change(tags.filter((_, i) => i !== index))
}
return (
<View className={cn('gap-[8px]', wrapperClassName)}>
{tags.length ? (
<View className="flex-row flex-wrap gap-[8px]">
{tags.map((tag, index) => (
<Chip key={index} label={tag} disabled={disabled} onRemove={() => remove(index)} />
))}
</View>
) : null}
<Input
ref={ref}
{...props}
editable={!disabled}
value={draft}
// RN docs: 'submit' sends onSubmitEditing without blurring, so the keyboard stays up for the next tag.
submitBehavior="submit"
onChangeText={(text) => {
if (disabled) return
pending.current = null
const parts = segments(text, delimiters)
if (parts.length === 1) return setDraft(text)
// trimStart: "a, b" should leave "b", not " b", in the field.
commit(parts.slice(0, -1), parts[parts.length - 1].trimStart(), text)
}}
onSubmitEditing={(event) => {
// Native submission can include a final IME/autocorrect edit before React renders its draft.
const text = event.nativeEvent.text
if (!disabled) commit(segments(text, delimiters), '', text)
onSubmitEditing?.(event)
}}
// RN docs: onKeyPress fires before onChange, so `draft` is still the pre-key text here.
// Android delivers soft-keyboard keys only; hardware-keyboard Backspace will not remove tags there.
onKeyPress={(event) => {
if (!disabled && event.nativeEvent.key === 'Backspace' && draft === '' && tags.length) {
remove(tags.length - 1)
}
onKeyPress?.(event)
}}
/>
</View>
)
},
)
TagsInput.displayName = 'TagsInput'
components/ui/tags-input/index.ts
export * from './TagsInput'