Primitives
Animated Number Avatar Badge Button Button Group Toggle Toggle Group Checkbox Chip Countdown Divider Fab Grid Icon Image Input Search Input Textarea Label Loader Marquee Masked Input Message Bubble Notification Banner Offline Banner Progress Progress Ring Radio Group Range Slider Rating Separator Skeleton Slider Stack Stepper Switch Text Theme Toggle Ticker Typing IndicatorComposed
Accordion Achievement Badge Action Bar Action Sheet Action Swap Activity Rings Add to Cart Button Address Card Agenda List Alert Amount Keypad Animated Icons App Bar Audio Message Audio Recorder Autocomplete Avatar Group Balance Display Bar List Barcode Before After Biometric Gate Bloom Menu Bottom Sheet Paywall Sheet Side Sheet Breadcrumb Calendar Calendar Strip Card Carousel Cart Item Character Charts Chat Composer Chat List Item Choice Card Circle Reveal Coach Marks Collapsible Collapsible Header Color Picker Combobox Command Palette Comment Thread Confetti Consent Sheet Context Menu Copy Field Country Picker Coupon Input Currency Input Data Table Date Range Picker Day Schedule Dialog Dock Donut Chart Drawer Driver Card Dropdown Menu Drum Picker Emoji Picker Empty State Error State Event Card Expandable Control Fader Feature Gate File Picker Filter Bar Follow Button Form Gauge Glass Glass Cluster Glass Dock Morph Glass Fab Morph Glass Lab Glass Orb Glass Search Morph Glass Sheet Edge Gradient Button Headline New Heatmap Image Cropper Image Viewer Kanban Card Keyboard Avoiding Keyboard Toolbar Leaderboard Level Progress Lightbox Like Button Line Chart List Reorderable List Swipeable Row Location Card Location Search Map Sheet Map View Markdown View Media Controls Media Picker Media Tile Mention Input Meter Bar Mini Player Mood Slider Morphing Modal Multi Select Navigation Rail Notification Item Number Input Onboarding Pager Order Card Order Summary OTP Input Pagination Paper Clip New Parallax Header Pass Card Password Strength Payment Button Payment Card Payment Method Permission Primer Phone Input PIN Pad Polaroid New Poll Popover Post Card Postage Stamp New Price Tag Pricing Table Product Card Product Gallery Profile Header Promo Banner Prompt Input Property Card Pull To Refresh QR Code Quick Actions Quick Replies Rating Summary Reaction Picker Resend Timer Review Card Review Prompt Ride Option Save Button Scan Frame Scroll Spy Tabs Seat Map Section Header Section Index Segmented Control Select Share Button Share Sheet Shutter Button Signature Pad Slide to Confirm Slot Picker Smart Banner Social Login Button Sparkline Splash Screen Split Button Stat Card Stateful Button Status Dot Step Flow Steps Sticker New Stopwatch Stories Progress Stories Viewer Story Ring Streak Counter Streaming Text Success Seal Swipe Deck Tabs Tag Input Tape New Text Reveal Thinking Indicator Time Picker Timeline Timer Ring Tip Selector Toast Toolbar Tooltip Track Row Transaction Row Trip Progress Variant Picker Video Controls Waveform Weather Card Weekday Picker Zoom TransitionScreens
Account Switcher Biometric Setup Delete Account Forgot Password Grow Auth Login Login — Dark Stage Login — Dense Work Login — Editorial Login — Illustrated Login — Minimal Ink Login — Social Login — Video Loop Food Onboarding Onboarding Onboarding Dark Objects Onboarding Editorial Onboarding Illustrated Onboarding Personalize Onboarding Photo Carousel OTP Verification Passkey — Create Password Reset Permission — Notifications Phone Verification Onboarding Quiz Session Devices Signup Sign-up Chat Sign-up Photo Sheet Social Auth Split Auth Verify Identity Welcome AI Chat AI Assistant Channels List Chat Info Chat List Chat Media Chat Thread Create Group Group Info Message Requests New Message Kept Messages Accessibility Activity Log Appearance Authenticator Blocked Accounts Export Your Data Downloads Edit Profile Edit Profile — Rows Emergency Call Empty States Set Error State Send Feedback Device Locator Help Center Home — Bento Home — Dark Home — Editorial Home Feed Invite Friends Language & Region Linked Accounts Not Found (404) Notification Settings Notifications Password Vault Paywall Paywall — Comparison Paywall — Dark Stage Paywall — Editorial Paywall — Photo Paywall — Trial Timeline Privacy Profile Profile — Gamified Profile — Minimal Profile — Photo Hero QR Scanner Report Issue Saved Items Phone Time Search Search — Command Palette Search — Visual Account Health Settings Settings — Dark Device Settings — Search Storage & Data Terms & Privacy Dating Chat Dating Filters Profile Discover Its A Match Into You Matches Profile Detail Profile Editor Courier Matching Delivery History Delivery Support Package Schedule Parcel Tracking Proof Of Delivery Quick Aisle Quick Home Send Package Substitutions Add Payment Address Book Cart Categories Checkout Checkout — Steps Checkout Success Delivery Filters & Sort Flash Sale Gift Cards Loyalty Points Order Cancel Order Detail Orders Pay Later Checkout Payment Methods Product Detail Product Detail — Hero Product Grid Product Reviews Promo Codes Recently Viewed Return Items Search Results Shop Assistant Store Home Tip & Rate Courier Order Tracking Wishlist Write a Review Event Checkin Event Hero Events Discover My Tickets Seat Selection Ticket Checkout Add Card Bank Accounts Dashboard — Bento Bill Pay Budgets Card Details Crypto Portfolio Finance Dashboard Dashboard — Dark Exchange Currency Expense List Invoice Detail Manage Cards Plan Management Savings Goals Send Money Spending Analytics Split Bill Subscriptions Token Detail Token Swap Transactions Wallet Home Wallet Movers Courier Tracking Food Cart Food Home Food Orders Grocery List Recipe Detail Restaurant — Dark Restaurant Detail Activity Rings Fitness Home Habit Quest Habit Tracker Meal Planner Med Store Meditation Player Mood Check-in Nutrition Home Period Tracker Prior Auth Prior Auth Cases Quest Complete Run Tracking Rx Scan Sleep Tracker Telehealth Booking Walk Map Water Tracker Workout Complete Workout Detail Workout Session Applications Apply Company Interview Schedule Job Detail Job Feed Resume Saved Jobs Create Listing Item Chat Listing Detail Make Offer Market Checkout Market Home Market Search My Listings Offers Inbox Seller Profile Audiobook Player Camera Gallery Albums Game Store Mini Player Music Player Photo Editor Photo Gallery Playlist Detail Podcast Player Clips Feed Serene Home Sound Mixer Stories Video Call Video Player Article Reader Course Detail Event Detail Memory Onboarding Icon Lab Leaderboard Lesson Player Match Detail News Editorial News Home Plant Care Prediction Live Prediction Welcome Smart Home Standings Ticket Wallet Topics Follow Weather Detail Add Task Sheet Alarm Clock Calendar Day Calendar Month Doc Scanner File Manager Focus Timer Journal Kanban Board Mail Inbox Mail Thread Note Editor Notes List Reminders Task List Time Blocks Agent Profile Compare Homes Mortgage Calculator Property Detail Rental Application Saved Homes Schedule Tour Search List Search Map Complete Destination Driver Arriving Ev Charging History Home In Trip Matching Options Parking Receipt Safety Schedule Scooter Unlock Booking Confirmed Booking Review Booking Slots My Bookings Pro On The Way Provider Detail Provider List Rate Service Services Home Arc Create Arc Detail Arc Onboarding Avatar Creator Comments Sheet Create Post Explore Grid Followers List Hashtag Feed Mentions Post Detail Post Hero Social Profile Boarding Pass Booking Confirm Car Rental Trip Discover Flight Live Flight Preferences Flight Results Flight Search Hotel Detail Live Transit Trip — Map Day Trip — Rideshare Request Seat Select Travel Home Trip Itinerary Trip OnboardingNothing matches — try another word.
Tag Input
Tag entry where what you type turns into a chip right where it is. Chips reflow smoothly as they’re added or removed, and a duplicate tag flickers its existing chip.
Preview
import * as React from "react";
import { forwardRef } from "react";
import { Pressable, Text, TextInput, View, type TextInputProps } from "react-native";
import Animated, {
Easing,
FadeOut,
LinearTransition,
useSharedValue,
useAnimatedStyle,
withSequence,
withSpring,
withTiming,
interpolateColor,
type SharedValue,
} from "react-native-reanimated";
import { cn, ease, spring, timing, useHaptic, useReducedMotion, useTheme } from "@lumioui/core";
import { Chip } from "../chip";
/** Flicker for "can't" — one 4px kick released into spring.shake, with a dip to 0.6. */
const FLICKER_KICK = 4;
const FLICKER_DIP = 0.6;
/** A new chip settles from a hair under size; its fill ignites over the next 120ms. */
const CHIP_FROM = 0.96;
const FILL_IGNITE = { duration: 120, easing: Easing.bezier(...ease.out) };
const IGNITE = { ...timing.fast, easing: Easing.bezier(...ease.out) };
/** Siblings and the caret reflow on the layout spring; removals dim in 120ms. */
const REFLOW = LinearTransition.springify().damping(spring.layout.damping).stiffness(spring.layout.stiffness);
const CHIP_EXIT = FadeOut.duration(timing.recede.duration);
/** One flicker: kick + dip, released on spring.shake. Reduced motion keeps the dip. */
function flicker(x: SharedValue<number>, o: SharedValue<number>, reduce: boolean) {
o.value = withSequence(withTiming(FLICKER_DIP, timing.instant), withTiming(1, IGNITE));
if (reduce) return;
x.value = FLICKER_KICK;
x.value = withSpring(0, spring.shake);
}
/** A committed tag. The typed text becomes the chip in place: the label is
* there at once, the chip settles 0.96 → 1 and its fill ignites behind it. */
function TagChip({
tag,
fresh,
flick,
reduce,
className,
onDelete,
}: {
tag: string;
fresh: boolean;
flick: number;
reduce: boolean;
className?: string;
onDelete?: () => void;
}) {
const scale = useSharedValue(fresh && !reduce ? CHIP_FROM : 1);
const fill = useSharedValue(fresh ? 0 : 1);
const x = useSharedValue(0);
const o = useSharedValue(1);
React.useEffect(() => {
scale.value = withSpring(1, spring.swap);
fill.value = withTiming(1, FILL_IGNITE);
}, [scale, fill]);
const lastFlick = React.useRef(flick);
React.useEffect(() => {
if (lastFlick.current === flick) return;
lastFlick.current = flick;
flicker(x, o, reduce);
}, [flick, reduce, x, o]);
const style = useAnimatedStyle(() => ({
opacity: o.value,
transform: [{ translateX: x.value }, { scale: scale.value }],
}));
const fillStyle = useAnimatedStyle(() => ({ opacity: fill.value }));
return (
<Animated.View layout={reduce ? undefined : REFLOW} exiting={CHIP_EXIT} style={style}>
<Animated.View pointerEvents="none" className="absolute inset-0 rounded-full bg-card" style={fillStyle} />
<Chip variant="input" size="sm" className={cn("bg-transparent", className)} onDelete={onDelete}>
{tag}
</Chip>
</Animated.View>
);
}
const DEFAULT_SEPARATORS = [",", " "];
function escapeRegExp(s: string) {
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
export type TagRejectReason = "duplicate" | "limit";
export interface TagInputProps
extends Omit<TextInputProps, "className" | "value" | "defaultValue" | "onChange" | "onChangeText" | "onSubmitEditing"> {
/** Controlled tag list. Omit for uncontrolled via `defaultValue`. */
value?: string[];
/** Uncontrolled initial tags. */
defaultValue?: string[];
/** Fires with the next tag list on every add/remove. */
onChange?: (tags: string[]) => void;
/** Visible label above the field. */
label?: string;
/** Placeholder inside the field — shown only while the tag list is empty. */
placeholder?: string;
/** Cap on tag count — commits past it are refused with a flicker. */
maxTags?: number;
/** Characters that commit a tag on top of Enter. Default [",", " "]. */
separators?: string[];
/** Called when a commit is rejected (duplicate or over maxTags). */
onReject?: (tag: string, reason: TagRejectReason) => void;
/** Locks the field — chips lose their ×, typing is disabled. */
disabled?: boolean;
/** Classes on the outer wrapper. */
className?: string;
/** Classes on the field box itself. */
fieldClassName?: string;
/** Classes on the inner TextInput. */
inputClassName?: string;
/** Classes merged onto every rendered chip. */
chipClassName?: string;
/** Show an "n of max" line under the field (needs `maxTags`); an
* over-limit commit flickers this line instead of the field. */
counter?: boolean;
}
/**
* TagInput — freeform token entry: type, hit Enter/comma/space and the text
* becomes a chip in place — its fill ignites while the caret reflows on the
* layout spring; Backspace on an empty field pops the last tag, which dims
* out as the gap closes. A duplicate flickers the chip it duplicates (the
* typed text stays); an over-limit commit flickers the counter or field.
* <TagInput value={tags} onChange={setTags} placeholder="Add labels…" />
* Expo Go compatible.
*/
export const TagInput = forwardRef<React.ElementRef<typeof TextInput>, TagInputProps>(
function TagInput(
{
value,
defaultValue,
onChange,
label,
placeholder,
maxTags,
separators = DEFAULT_SEPARATORS,
onReject,
disabled,
editable = true,
className,
fieldClassName,
inputClassName,
chipClassName,
counter = false,
onKeyPress,
onFocus,
onBlur,
...props
},
ref
) {
const { colors } = useTheme();
const haptics = useHaptic();
const reduce = useReducedMotion();
const inputRef = React.useRef<TextInput>(null);
const isDisabled = disabled || !editable;
const [internal, setInternal] = React.useState<string[]>(defaultValue ?? []);
const tags = value ?? internal;
const [text, setText] = React.useState("");
// Tags present at mount are at rest; only later commits perform.
const [mountTags] = React.useState(tags);
/** Per-tag flicker counters (lower-cased key) — bumping one flickers that chip. */
const [flicks, setFlicks] = React.useState<Record<string, number>>({});
const shakeX = useSharedValue(0);
const fieldO = useSharedValue(1);
const countX = useSharedValue(0);
const countO = useSharedValue(1);
const focusT = useSharedValue(0);
const fieldStyle = useAnimatedStyle(() => ({ opacity: fieldO.value, transform: [{ translateX: shakeX.value }] }));
const countStyle = useAnimatedStyle(() => ({ opacity: countO.value, transform: [{ translateX: countX.value }] }));
const showCounter = counter && maxTags !== undefined;
const borderStyle = useAnimatedStyle(() => ({
borderColor: interpolateColor(focusT.value, [0, 1], [colors.input, colors.ring]),
}));
const apply = React.useCallback(
(next: string[]) => {
if (value === undefined) setInternal(next);
onChange?.(next);
},
[value, onChange]
);
const reject = React.useCallback(
(tag: string, reason: TagRejectReason) => {
// Point at the cause: the chip it duplicates, the counter, else the field.
const existing = reason === "duplicate" ? tags.find((t) => t.toLowerCase() === tag.toLowerCase()) : undefined;
if (existing) {
const k = existing.toLowerCase();
setFlicks((f) => ({ ...f, [k]: (f[k] ?? 0) + 1 }));
} else if (reason === "limit" && showCounter) {
flicker(countX, countO, reduce);
} else {
flicker(shakeX, fieldO, reduce);
}
haptics.warning();
onReject?.(tag, reason);
},
[tags, showCounter, reduce, shakeX, fieldO, countX, countO, haptics, onReject]
);
/** Why `tag` can't join `current`, or null when it may. Case-insensitive
* duplicate guard + maxTags cap. */
const checkTag = React.useCallback(
(tag: string, current: string[]): TagRejectReason | null => {
if (current.some((t) => t.toLowerCase() === tag.toLowerCase())) return "duplicate";
if (maxTags !== undefined && current.length >= maxTags) return "limit";
return null;
},
[maxTags]
);
/** Commit one token. Returns true when the text should leave the field. */
const commit = React.useCallback(
(raw: string): boolean => {
const tag = raw.trim();
if (!tag) return true;
const reason = checkTag(tag, tags);
if (reason) {
reject(tag, reason);
return false;
}
haptics.selection();
apply([...tags, tag]);
return true;
},
[tags, checkTag, apply, reject, haptics]
);
const remove = React.useCallback(
(tag: string) => {
haptics.light();
apply(tags.filter((t) => t !== tag));
},
[tags, apply, haptics]
);
const handleChangeText = (next: string) => {
const re = new RegExp(separators.map(escapeRegExp).join("|"));
if (!re.test(next)) {
setText(next);
return;
}
const parts = next.split(re);
const tail = parts.pop() ?? "";
// Every chunk before a separator is a commit attempt against the list
// PLUS what's already been added this keystroke — a pasted "a,a" can't
// double-commit before state lands. Rejected chunks stay in the field
// (joined back with the tail) so the user can edit.
const kept: string[] = [];
const added: string[] = [];
for (const part of parts) {
const tag = part.trim();
if (!tag) continue;
const reason = checkTag(tag, [...tags, ...added]);
if (reason) {
reject(tag, reason);
kept.push(tag);
continue;
}
added.push(tag);
}
if (added.length > 0) {
haptics.selection();
apply([...tags, ...added]);
}
setText([...kept, tail].join(" ").trimStart());
};
const handleSubmit = () => {
if (commit(text)) setText("");
};
const handleKeyPress = (e: Parameters<NonNullable<TextInputProps["onKeyPress"]>>[0]) => {
// Backspace on an empty field pops the last tag — the classic
// token-field idiom (a mail To: line).
if (e.nativeEvent.key === "Backspace" && text === "" && tags.length > 0) {
remove(tags[tags.length - 1]!);
}
onKeyPress?.(e);
};
const describedId = React.useId();
return (
<View className={cn("w-full gap-2", className)}>
{label ? (
<Text nativeID={`${describedId}-label`} className="text-sm font-medium text-foreground">
{label}
</Text>
) : null}
<Pressable
// Not itself a control — taps on the padding area just forward
// focus to the inner TextInput, which owns the a11y contract.
accessible={false}
accessibilityRole="none"
onPress={() => !isDisabled && inputRef.current?.focus()}
disabled={isDisabled}
>
<Animated.View
style={fieldStyle}
className={cn("rounded-xl", isDisabled && "opacity-50")}
>
<Animated.View
style={borderStyle}
className={cn(
"min-h-[48px] flex-row flex-wrap items-center gap-2 rounded-xl border-[1.5px] bg-background px-3 py-2",
fieldClassName
)}
>
{tags.map((tag) => (
<TagChip
key={tag}
tag={tag}
fresh={!mountTags.includes(tag)}
flick={flicks[tag.toLowerCase()] ?? 0}
reduce={reduce}
className={chipClassName}
onDelete={isDisabled ? undefined : () => remove(tag)}
/>
))}
<Animated.View layout={reduce ? undefined : REFLOW} className="flex-1" style={{ minWidth: 90 }}>
<TextInput
ref={(node) => {
(inputRef as React.MutableRefObject<TextInput | null>).current = node;
if (typeof ref === "function") ref(node);
else if (ref) (ref as React.MutableRefObject<TextInput | null>).current = node;
}}
value={text}
onChangeText={handleChangeText}
onSubmitEditing={handleSubmit}
onKeyPress={handleKeyPress}
editable={!isDisabled}
placeholder={tags.length === 0 ? placeholder : undefined}
placeholderTextColor={colors.mutedForeground}
className={cn("w-full py-1 text-base text-foreground", inputClassName)}
autoCapitalize="none"
autoCorrect={false}
onFocus={(e) => {
focusT.value = reduce ? 1 : withTiming(1, timing.fast);
onFocus?.(e);
}}
onBlur={(e) => {
focusT.value = reduce ? 0 : withTiming(0, timing.fast);
onBlur?.(e);
}}
accessibilityLabel={label ?? props.accessibilityLabel ?? placeholder ?? "Tags"}
accessibilityLabelledBy={label ? `${describedId}-label` : undefined}
aria-labelledby={label ? `${describedId}-label` : undefined}
accessibilityHint="Type and press return, comma or space to add a tag. Backspace removes the last tag."
accessibilityState={{ disabled: isDisabled }}
blurOnSubmit={false}
returnKeyType="done"
{...props}
/>
</Animated.View>
</Animated.View>
</Animated.View>
</Pressable>
{showCounter ? (
<Animated.View style={countStyle}>
<Text className="text-[13px] tabular-nums text-muted-foreground" accessibilityLiveRegion="polite">
{tags.length} of {maxTags}
</Text>
</Animated.View>
) : null}
</View>
);
}
);
TagInput.displayName = "TagInput"; import { TagInput } from "@/components/ui/tag-input/tag-input";
export function Example() {
return (
<TagInput />
);
} Installation
Install the dependencies
npx expo install react-native-reanimatedAdd the components it builds on
Copy the source from the Code tab into your project
components/ui/tag-input/tag-input.tsxcomponents/ui/tag-input/index.tsUpdate the import paths to match your project setup.
Usage
import { TagInput } from "@/components/ui/tag-input/tag-input"; <TagInput /> API reference
value string[] Controlled tag list. Omit for uncontrolled via defaultValue.
defaultValue string[] Uncontrolled initial tags.
—onChange (tags: string[]) => void Fires with the next tag list on every add/remove.
—label string Visible label above the field.
—placeholder string Placeholder inside the field — shown only while the tag list is empty.
—maxTags number Cap on tag count — commits past it are refused with a flicker.
—separators string[] Characters that commit a tag on top of Enter. Default [",", " "].
DEFAULT_SEPARATORS onReject (tag: string, reason: TagRejectReason) = …
(tag: string, reason: TagRejectReason) => void Called when a commit is rejected (duplicate or over maxTags).
—disabled boolean Locks the field — chips lose their ×, typing is disabled.
—className string Classes on the outer wrapper.
—fieldClassName string Classes on the field box itself.
—inputClassName string Classes on the inner TextInput.
—chipClassName string Classes merged onto every rendered chip.
—counter boolean Show an "n of max" line under the field (needs maxTags); an over-limit commit flickers this line instead of the field.
false