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.
Autocomplete
Search field with live suggestions that highlight the letters you’ve typed. Shows recent searches while empty and a loading state, and picking a row lifts it straight into the field.
Preview
import * as React from "react";
import { forwardRef, useMemo, useState } from "react";
import { Keyboard, Pressable, Text, TextInput, View, type ViewProps } from "react-native";
import Animated, {
Easing,
runOnJS,
useAnimatedStyle,
useSharedValue,
withDelay,
withSpring,
withTiming,
type SharedValue,
} from "react-native-reanimated";
import {
AnimatedPressable,
SWITCH_DIM,
Sheen,
SwitchOn,
cn,
ease,
rowDelay,
spring,
tempo,
timing,
useHaptic,
usePressAnimation,
useReducedMotion,
useTheme,
} from "@lumioui/core";
import { Icon, type IconName } from "../icon";
import { SearchInput, type SearchInputProps } from "../search-input";
import { Skeleton } from "../skeleton";
/**
* Autocomplete — a search field with live suggestions where light follows
* input: the typed letters of each title are lit in full ink while the rest
* sits dim, so typing visibly lights the list. Recents while the query is
* empty, dim structure while results load (one light pass as rows switch
* on, 40ms apart), and an honest empty state. Picking a row lifts its title
* into the field while the siblings dim; the dropdown then dims out.
* "inline" lists suggestions under the field (a full search screen);
* "dropdown" floats them in a card under a form field (address entry).
*
* <Autocomplete options={places} recent={recents} onSelect={(o) => go(o)} />
*
* Expo Go compatible.
*/
export interface AutocompleteOption {
/** Stable id. */
id: string;
/** Main line — the highlighted match runs here. */
title: string;
/** Second line (address, airport city, handle). */
subtitle?: string;
/** Leading glyph in a round disc. Defaults to search (clock for recents). */
icon?: IconName;
/** Custom leading node (avatar, logo) — wins over `icon`. */
leading?: React.ReactNode;
/** Trailing node (distance, code, badge). */
trailing?: React.ReactNode;
/** Extra words matched by the built-in filter but not shown. */
keywords?: string;
}
/** Built-in ranking: title prefix → word prefix → substring → keyword. */
export function filterOptions(options: AutocompleteOption[], query: string): AutocompleteOption[] {
const q = query.trim().toLowerCase();
if (!q) return [];
const scored: { o: AutocompleteOption; s: number }[] = [];
for (const o of options) {
const t = o.title.toLowerCase();
const sub = (o.subtitle ?? "").toLowerCase();
const kw = (o.keywords ?? "").toLowerCase();
let s = -1;
if (t.startsWith(q)) s = 0;
else if (t.split(/[\s,-]+/).some((w) => w.startsWith(q))) s = 1;
else if (t.includes(q)) s = 2;
else if (sub.includes(q) || kw.split(/\s+/).some((w) => w.startsWith(q))) s = 3;
if (s >= 0) scored.push({ o, s });
}
return scored.sort((a, b) => a.s - b.s).map((r) => r.o);
}
/** Untyped letters sit at this share of the ink, so typing visibly lights the list. */
const UNLIT = 0.55;
/** Siblings of a picked row dim to here while it lifts into the field. */
const SIBLING_DIM = 0.35;
/** The picked row travels to the field on one settle beat; the field fills as it lands. */
const LIFT_MS = tempo.settle;
/** It dims out over the last recede of that travel, so it melts into the field text. */
const LIFT_FADE_AT = tempo.settle - timing.recede.duration;
/** Dropdown dims to this scale as it leaves (overlay exit, DESIGN-TASTE §5b). */
const EXIT_SCALE = 0.97;
/** Height of the input box inside the field — the lift aims at its centre. */
const INPUT_H = 48;
/** "#RRGGBB" + alpha → "#RRGGBBAA"; other colour formats pass through. */
function withAlpha(color: string, a: number) {
if (!/^#[0-9a-f]{6}$/i.test(color)) return color;
return `${color}${Math.round(a * 255).toString(16).padStart(2, "0")}`;
}
/** Title lit by the query: the typed letters are full ink, the rest sits dim. */
function Highlighted({ text, query, enabled }: { text: string; query: string; enabled: boolean }) {
const { colors } = useTheme();
const q = query.trim();
const i = enabled && q ? text.toLowerCase().indexOf(q.toLowerCase()) : -1;
if (i < 0) {
return (
<Text className="text-base text-foreground" numberOfLines={1}>
{text}
</Text>
);
}
return (
<Text className="text-base" style={{ color: withAlpha(colors.foreground, UNLIT) }} numberOfLines={1}>
{text.slice(0, i)}
<Text className="text-foreground">{text.slice(i, i + q.length)}</Text>
{text.slice(i + q.length)}
</Text>
);
}
function OptionRow({
option,
query,
highlight,
fallbackIcon,
onPress,
}: {
option: AutocompleteOption;
query: string;
highlight: boolean;
fallbackIcon: IconName;
onPress: (o: AutocompleteOption) => void;
}) {
const press = usePressAnimation({ pressedScale: 0.99, pressedOpacity: 0.6 });
return (
<AnimatedPressable
onPress={() => onPress(option)}
onPressIn={press.onPressIn}
onPressOut={press.onPressOut}
style={press.animatedStyle}
className="min-h-14 flex-row items-center gap-3 px-4 py-2"
accessibilityRole="button"
accessibilityLabel={[option.title, option.subtitle].filter(Boolean).join(", ")}
>
{option.leading ?? (
<View className="h-9 w-9 items-center justify-center rounded-full bg-secondary">
<Icon name={option.icon ?? fallbackIcon} size="sm" color="foreground" />
</View>
)}
<View className="min-w-0 flex-1 gap-0.5">
<Highlighted text={option.title} query={query} enabled={highlight} />
{option.subtitle ? (
<Text className="text-sm text-muted-foreground" numberOfLines={1}>
{option.subtitle}
</Text>
) : null}
</View>
{option.trailing}
</AnimatedPressable>
);
}
/**
* One suggestion in the list. It switches on in its slot (dim → on, 40ms row
* rhythm); when a sibling is picked it dims; when it is picked it lifts into
* the field and melts into the text there.
*/
function SuggestionRow({
index,
picked,
pickSV,
liftTo,
separator,
children,
}: {
index: number;
picked: boolean;
pickSV: SharedValue<number>;
/** Offset from the list's top to the input's centre (negative = above). */
liftTo: number;
separator: boolean;
children: React.ReactNode;
}) {
const reduce = useReducedMotion();
const y = React.useRef(0);
const h = React.useRef(0);
const lift = useSharedValue(0);
const self = useSharedValue(1);
const was = React.useRef(picked);
React.useEffect(() => {
if (picked && !was.current) {
if (!reduce) lift.value = withSpring(liftTo - y.current - h.current / 2, spring.surface);
self.value = withDelay(LIFT_FADE_AT, withTiming(0, { ...timing.recede, easing: Easing.bezier(...ease.in) }));
} else if (!picked && was.current) {
// Landed — it is back in its slot as the one match, switching on again.
lift.value = 0;
self.value = SWITCH_DIM;
self.value = withTiming(1, { ...timing.fast, easing: Easing.bezier(...ease.out) });
}
was.current = picked;
}, [picked, reduce, liftTo, lift, self]);
const style = useAnimatedStyle(() => ({
opacity: picked ? self.value : 1 - (1 - SIBLING_DIM) * pickSV.value,
transform: [{ translateY: lift.value }],
zIndex: picked ? 1 : 0,
}));
return (
<Animated.View
style={style}
onLayout={(e) => {
y.current = e.nativeEvent.layout.y;
h.current = e.nativeEvent.layout.height;
}}
>
<SwitchOn delay={rowDelay(index)}>
{separator ? <View className="ml-16 h-px bg-border" /> : null}
{children}
</SwitchOn>
</Animated.View>
);
}
export interface AutocompleteProps extends Omit<ViewProps, "className"> {
/** Controlled query text. */
value?: string;
/** Uncontrolled initial query. */
defaultValue?: string;
/** Fires on every keystroke (debounce in your fetcher if remote). */
onValueChange?: (query: string) => void;
/** Candidate options. Filtered by the built-in ranking unless `filter`
* is false (then pass already-filtered results). */
options?: AutocompleteOption[];
/** Custom filter, or `false` to show `options` as-is (remote search). */
filter?: ((options: AutocompleteOption[], query: string) => AutocompleteOption[]) | false;
/** Shown while the query is empty. */
recent?: AutocompleteOption[];
/** Header above recents. Default "Recent". */
recentTitle?: string;
/** Shows a "Clear" action on the recent header. */
onClearRecent?: () => void;
/** Header above matches. Omit for none. */
resultsTitle?: string;
/** Fires when a suggestion is picked. */
onSelect?: (option: AutocompleteOption) => void;
/** Fill the field with the picked title. Default true. */
fillOnSelect?: boolean;
/** Skeleton rows while results load. */
loading?: boolean;
/** Max rows shown. Default 6. */
maxResults?: number;
/** Characters before matching starts. Default 1. */
minChars?: number;
/** Bold the typed part of each title. Default true. */
highlightMatch?: boolean;
/** Empty-results copy. Default `No results for "<query>"`. */
emptyText?: string | ((query: string) => string);
/** "inline" (default) list under the field, always visible; "dropdown"
* floating card shown while the field is focused. */
presentation?: "inline" | "dropdown";
/** Controlled suggestion visibility. */
open?: boolean;
/** Fires when suggestions open/close (focus, pick, blur). */
onOpenChange?: (open: boolean) => void;
/** Field placeholder. Default "Search". */
placeholder?: string;
/** Label above the field. */
label?: string;
/** Extra props for the SearchInput field. */
inputProps?: Omit<SearchInputProps, "value" | "onChangeText" | "placeholder" | "label">;
/** Content shown under recents while the query is empty (shortcuts). */
emptyQueryContent?: React.ReactNode;
className?: string;
}
export const Autocomplete = forwardRef<React.ElementRef<typeof TextInput>, AutocompleteProps>(function Autocomplete(
{
value,
defaultValue = "",
onValueChange,
options = [],
filter,
recent,
recentTitle = "Recent",
onClearRecent,
resultsTitle,
onSelect,
fillOnSelect = true,
loading,
maxResults = 6,
minChars = 1,
highlightMatch = true,
emptyText,
presentation = "inline",
open: controlledOpen,
onOpenChange,
placeholder = "Search",
label,
inputProps,
emptyQueryContent,
className,
...props
},
ref
) {
const haptics = useHaptic();
const reduceMotion = useReducedMotion();
const { dark } = useTheme();
const [internal, setInternal] = useState(defaultValue);
const query = value ?? internal;
const [focused, setFocused] = useState(false);
const dropdown = presentation === "dropdown";
const [lifting, setLifting] = useState(false);
// The dropdown stays up while a picked row lifts into the field, even
// though the keyboard (and focus) left at the tap.
const open = controlledOpen ?? (dropdown ? focused || lifting : true);
const setQuery = (q: string) => {
if (value === undefined) setInternal(q);
onValueChange?.(q);
};
const setFocus = (f: boolean) => {
setFocused(f);
if (dropdown && controlledOpen === undefined) onOpenChange?.(f);
};
const active = query.trim().length >= minChars;
const matches = useMemo(() => {
if (!active) return [];
const list = filter === false ? options : (filter ?? filterOptions)(options, query);
return list.slice(0, maxResults);
}, [active, filter, options, query, maxResults]);
// Pick — the touched row leads: it lifts into the field while siblings
// dim, the field fills as it lands, then the dropdown dims out.
const [pickedId, setPickedId] = useState<string | null>(null);
const pickSV = useSharedValue(0);
const landing =React.useRef<ReturnType<typeof setTimeout> | null>(null);
const blurring = React.useRef<ReturnType<typeof setTimeout> | null>(null);
React.useEffect(
() => () => {
if (landing.current) clearTimeout(landing.current);
if (blurring.current) clearTimeout(blurring.current);
},
[]
);
const pick = (o: AutocompleteOption) => {
if (lifting) return;
haptics.selection();
Keyboard.dismiss();
setLifting(true);
setPickedId(o.id);
pickSV.value = withTiming(1, { ...timing.recede, easing: Easing.bezier(...ease.in) });
landing.current = setTimeout(
() => {
landing.current = null;
setLifting(false);
if (fillOnSelect) setQuery(o.title);
setFocused(false);
onOpenChange?.(false);
onSelect?.(o);
// Inline lists stay: the picked row switches on again in its slot.
if (!dropdown) {
setPickedId(null);
pickSV.value = withTiming(0, timing.fast);
}
},
reduceMotion ? timing.fast.duration : LIFT_MS
);
};
// Loading → loaded: one light pass crosses the list as the rows switch on.
const [lit, setLit] = useState(0);
const [wasLoading, setWasLoading] = useState(!!loading);
if (wasLoading !== !!loading) {
setWasLoading(!!loading);
if (!loading) setLit((n) => n + 1);
}
const siblingStyle = useAnimatedStyle(() => ({ opacity: 1 - (1 - SIBLING_DIM) * pickSV.value }));
const header = (title: string, action?: { label: string; onPress: () => void }) => (
<Animated.View style={siblingStyle} className="flex-row items-center justify-between px-4 pb-1 pt-3">
<Text className="text-[13px] text-muted-foreground" accessibilityRole="header">
{title}
</Text>
{action ? (
<Pressable onPress={action.onPress} hitSlop={10} accessibilityRole="button" accessibilityLabel={`${action.label} ${title}`}>
<Text className="text-[13px] font-semibold text-primary-text">{action.label}</Text>
</Pressable>
) : null}
</Animated.View>
);
// The input box is the bottom INPUT_H of the field; the list starts mt-2
// under it (dropdown card) or pt-1 (inline). Aim the lift at its centre.
const liftTo = -(dropdown ? 8 : 4) - INPUT_H / 2;
const rows = (list: AutocompleteOption[], icon: IconName) =>
list.map((o, i) => (
<SuggestionRow
key={o.id}
index={i}
picked={pickedId === o.id}
pickSV={pickSV}
liftTo={liftTo}
separator={i > 0}
>
<OptionRow option={o} query={query} highlight={highlightMatch} fallbackIcon={icon} onPress={pick} />
</SuggestionRow>
));
let body: React.ReactNode;
if (!active) {
body =
recent?.length || emptyQueryContent ? (
<>
{recent?.length ? (
<>
{header(recentTitle, onClearRecent ? { label: "Clear", onPress: () => { haptics.light(); onClearRecent(); } } : undefined)}
{rows(recent, "clock")}
</>
) : null}
{emptyQueryContent}
</>
) : null;
} else if (loading && !matches.length) {
// Dim structure in the exact shape of the rows it is waiting for.
body = (
<View className="gap-4 px-4 py-3" accessibilityLabel="Loading suggestions" accessibilityState={{ busy: true }}>
{[0.7, 0.5, 0.6].map((w, i) => (
<View key={i} className="flex-row items-center gap-3">
<Skeleton className="h-9 w-9 rounded-full" />
<View className="flex-1 gap-1.5">
<Skeleton className="h-4 rounded-md" style={{ width: `${w * 100}%` }} />
<Skeleton className="h-3 rounded-md" style={{ width: `${w * 70}%` }} />
</View>
</View>
))}
</View>
);
} else if (!matches.length) {
const copy = typeof emptyText === "function" ? emptyText(query.trim()) : (emptyText ?? `No results for "${query.trim()}"`);
body = (
<SwitchOn className="items-center px-6 py-8" accessibilityLiveRegion="polite">
<Text className="text-center text-[15px] text-muted-foreground">{copy}</Text>
</SwitchOn>
);
} else {
body = (
<>
{resultsTitle ? header(resultsTitle) : null}
{rows(matches, "search")}
</>
);
}
// Dropdown card — container then content: the card ignites from its
// anchor while rows switch on inside it, and it leaves by dimming in place.
const shown = !!(open && body);
const [mounted, setMounted] = useState(shown);
const [prevShown, setPrevShown] = useState(shown);
if (prevShown !== shown) {
setPrevShown(shown);
if (shown) {
setMounted(true);
// A fresh opening forgets the last pick.
if (pickedId) setPickedId(null);
}
}
const glow = useSharedValue(shown ? 1 : 0);
const rise = useSharedValue(0);
const shrink = useSharedValue(1);
React.useEffect(() => {
if (!dropdown) return;
if (shown) {
pickSV.value = 0;
glow.value = withTiming(1, { ...timing.fast, easing: Easing.bezier(...ease.out) });
shrink.value = 1;
if (reduceMotion) {
rise.value = 0;
} else {
rise.value = -6;
rise.value = withSpring(0, spring.surface);
}
} else {
glow.value = withTiming(0, { ...timing.recede, easing: Easing.bezier(...ease.in) }, (done) => {
if (done) runOnJS(setMounted)(false);
});
if (!reduceMotion) shrink.value = withTiming(EXIT_SCALE, timing.recede);
}
}, [shown, dropdown, reduceMotion, glow, rise, shrink, pickSV]);
const cardStyle = useAnimatedStyle(() => ({
opacity: glow.value,
transform: [{ translateY: rise.value }, { scale: shrink.value }],
}));
const list = (
<>
{body}
<Sheen run={lit} strength={dark ? 0.14 : 0.45} />
</>
);
return (
<View className={cn("w-full", dropdown && "z-10", className)} {...props}>
<SearchInput
ref={ref}
value={query}
onChangeText={setQuery}
placeholder={placeholder}
label={label}
autoCorrect={false}
{...inputProps}
onFocus={(e) => {
setFocus(true);
inputProps?.onFocus?.(e);
}}
onBlur={(e) => {
// Let a row tap land before the dropdown closes.
if (blurring.current) clearTimeout(blurring.current);
blurring.current = setTimeout(() => setFocus(false), timing.recede.duration);
inputProps?.onBlur?.(e);
}}
/>
{dropdown ? (
mounted && body ? (
<Animated.View
style={cardStyle}
pointerEvents={shown ? "auto" : "none"}
// While a row lifts out of the card it must not be clipped.
className={cn(
"absolute left-0 right-0 top-full mt-2 rounded-2xl border border-border bg-popover pb-1",
!pickedId && "overflow-hidden"
)}
accessibilityRole="list"
>
{list}
</Animated.View>
) : null
) : open && body ? (
<View className={cn("pt-1", !pickedId && "overflow-hidden")} accessibilityRole="list">
{list}
</View>
) : null}
</View>
);
});
Autocomplete.displayName = "Autocomplete"; import { Autocomplete } from "@/components/ui/autocomplete/autocomplete";
export function Example() {
return (
<Autocomplete />
);
} 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/autocomplete/autocomplete.tsxcomponents/ui/autocomplete/index.tsUpdate the import paths to match your project setup.
Usage
import { filterOptions, Autocomplete } from "@/components/ui/autocomplete/autocomplete"; <Autocomplete /> Also exported: filterOptions.
Examples
The delivery address step in a food app.
import * as React from "react";
import { TextInput, View } from "react-native";
import { Accent, useTheme } from "@lumioui/core";
import { Autocomplete, type AutocompleteOption } from "../autocomplete";
import { Button } from "../../button/button";
import { Icon } from "../../icon/icon";
import { Text } from "../../text/text";
interface Address {
line: string;
city: string;
postcode: string;
}
const ADDRESSES: (AutocompleteOption & { address: Address })[] = [
{ id: "1", title: "12 Chandler Street", subtitle: "Harbourside HS1 3HW", icon: "map-pin", address: { line: "12 Chandler Street", city: "Harbourside", postcode: "HS1 3HW" } },
{ id: "2", title: "12 Chandos Road", subtitle: "Ashby, Harbourside HS27 4AF", icon: "map-pin", address: { line: "12 Chandos Road", city: "Ashby", postcode: "HS27 4AF" } },
{ id: "3", title: "12 Chandler Place", subtitle: "Westbrook HS21 9AQ", icon: "map-pin", address: { line: "12 Chandler Place", city: "Harbourside", postcode: "HS21 9AQ" } },
{ id: "4", title: "12 Chapel Street", subtitle: "Mill Quarter HS4 1PW", icon: "map-pin", address: { line: "12 Chapel Street", city: "Harbourside", postcode: "HS4 1PW" } },
{ id: "5", title: "120 Oldfield Street", subtitle: "Canal Side HS4 1LJ", icon: "map-pin", address: { line: "120 Oldfield Street", city: "Harbourside", postcode: "HS4 1LJ" } },
];
function Field({ label, value, placeholder }: { label: string; value: string; placeholder: string }) {
const { colors } = useTheme();
return (
<View className="gap-1.5">
<Text className="text-sm font-medium">{label}</Text>
<TextInput
value={value}
editable={false}
placeholder={placeholder}
placeholderTextColor={colors.mutedForeground}
className="h-12 rounded-xl border-[1.5px] border-input bg-background px-3.5 text-base text-foreground"
accessibilityLabel={label}
/>
</View>
);
}
/** AutocompleteAddress — the delivery address step in a food app. The
* dropdown floats under the street field while it's focused; picking a
* suggestion fills city and postcode below and unlocks Save. Orange. */
export function AutocompleteAddress() {
const [picked, setPicked] = React.useState<Address | null>(null);
const [query, setQuery] = React.useState("12 cha");
return (
<Accent color="orange" className="w-full">
<View className="w-full gap-6">
<View className="gap-1 px-1">
<Text className="text-2xl font-bold tracking-tight">Delivery address</Text>
<Text variant="muted">Drivers use this to find you</Text>
</View>
<View className="gap-4">
<Autocomplete
presentation="dropdown"
label="Street address"
value={query}
onValueChange={(q) => {
setQuery(q);
setPicked(null);
}}
options={ADDRESSES}
onSelect={(o) => {
const hit = ADDRESSES.find((a) => a.id === o.id);
if (hit) setPicked(hit.address);
}}
placeholder="Start typing your address"
emptyText="No address found. Check the house number."
inputProps={{ icon: <Icon name="map-pin" size="sm" color="mutedForeground" /> }}
/>
<View className="flex-row gap-3">
<View className="flex-1">
<Field label="City" value={picked?.city ?? ""} placeholder="Filled from your address" />
</View>
<View className="w-32">
{/* Short placeholder — the 128pt column can't hold the city's sentence. */}
<Field label="Postcode" value={picked?.postcode ?? ""} placeholder="Auto-filled" />
</View>
</View>
</View>
<Button size="lg" className="w-full" disabled={!picked}>
Save address
</Button>
</View>
</Accent>
);
} The To field of a rail ticket.
import * as React from "react";
import { View } from "react-native";
import { SwitchOn } from "@lumioui/core";
import { Autocomplete, type AutocompleteOption } from "../autocomplete";
import { Icon } from "../../icon/icon";
import { Text } from "../../text/text";
const mins = (m: number) => <Text className="text-sm tabular-nums text-muted-foreground">{`${m} min`}</Text>;
const STATIONS: AutocompleteOption[] = [
{ id: "alx", title: "Alder Cross", subtitle: "Coast line · platforms 1–4", icon: "tram-front", trailing: mins(14), keywords: "aldx" },
{ id: "alj", title: "Alderbrook Junction", subtitle: "Change for the Valley line", icon: "tram-front", trailing: mins(26) },
{ id: "ash", title: "Ashby Parkway", subtitle: "Park and ride · 1,200 spaces", icon: "car", trailing: mins(33) },
{ id: "pal", title: "Palmer Street", subtitle: "City loop", icon: "tram-front", trailing: mins(6), keywords: "loop" },
{ id: "kbay", title: "Kestrel Bay", subtitle: "Ferry connection", icon: "map-pin", trailing: mins(41), keywords: "ferry harbour" },
{ id: "kmr", title: "Kingsmere", subtitle: "Coast line", icon: "tram-front", trailing: mins(52) },
{ id: "lq", title: "Lumen Quay", subtitle: "Waterfront · step-free", icon: "tram-front", trailing: mins(9), keywords: "waterfront" },
{ id: "air", title: "Northgate Airport", subtitle: "Terminal shuttle every 10 min", icon: "plane", trailing: mins(38), keywords: "airport flights" },
{ id: "mill", title: "Old Mill Halt", subtitle: "Request stop", icon: "map-pin", trailing: mins(47) },
];
const RECENT: AutocompleteOption[] = [
{ id: "home", title: "Lumen Quay", subtitle: "Home station", icon: "home" },
{ id: "work", title: "Palmer Street", subtitle: "Work · weekday mornings", icon: "briefcase" },
{ id: "kbay-r", title: "Kestrel Bay", subtitle: "Last Saturday" },
];
/** AutocompletePlaces — the To field of a rail ticket. Typed letters light
* up in each station name while the rest sits dim (it opens on "al").
* Picking a station lifts it into the field, then the ticket line below
* switches on with the next departure. Ink. */
export function AutocompletePlaces() {
const [query, setQuery] = React.useState("al");
const [dest, setDest] = React.useState<AutocompleteOption | null>(null);
return (
<View className="w-full gap-4">
<View className="gap-3">
<Text className="px-1 text-2xl font-bold tracking-tight">Where to?</Text>
<View className="flex-row items-center gap-3 px-1">
<View className="h-2.5 w-2.5 rounded-full bg-foreground" />
<Text className="flex-1 text-[15px] text-muted-foreground">From: Harbourside Central</Text>
</View>
</View>
<Autocomplete
value={query}
onValueChange={(q) => {
setQuery(q);
setDest(null);
}}
options={STATIONS}
recent={RECENT}
onSelect={setDest}
placeholder="Search stations"
emptyText={(q) => `No station matches "${q}". Try a town or a stop name.`}
/>
{dest ? (
<SwitchOn className="flex-row items-center gap-3 rounded-2xl bg-card p-4">
<Icon name="tram-front" size="md" color="foreground" />
<View className="flex-1">
<Text className="text-[15px] font-semibold">{`Harbourside Central → ${dest.title}`}</Text>
<Text variant="muted">Next train 08:42 · platform 3 · off-peak single</Text>
</View>
</SwitchOn>
) : null}
</View>
);
} "Send to" in a money app.
import * as React from "react";
import { View } from "react-native";
import { Accent } from "@lumioui/core";
import { Autocomplete, type AutocompleteOption } from "../autocomplete";
import { Avatar } from "../../avatar/avatar";
import { Button } from "../../button/button";
import { Text } from "../../text/text";
const person = (id: string, name: string, handle: string, img: number, keywords?: string): AutocompleteOption => ({
id,
title: name,
subtitle: handle,
keywords,
leading: <Avatar size="md" source={{ uri: `https://i.pravatar.cc/150?img=${img}` }} fallback={name.slice(0, 1)} />,
});
const PEOPLE: AutocompleteOption[] = [
person("mk", "Mateo Kovač", "@mateok · Climbing club", 12, "mateo"),
person("ml", "Maya Lindqvist", "@mayal · 07700 900461", 32),
person("mr", "Marcus Reid", "@marcusreid", 15),
person("ms", "Mira Santos", "@mira.s · Flatmate", 45, "rent"),
person("jt", "Jonah Tran", "@jonaht", 53),
person("ea", "Elif Arslan", "@elif", 24),
person("ao", "Ada Obi", "@adaobi", 9),
];
const RECENT = [PEOPLE[3], PEOPLE[4], PEOPLE[0]].filter((p): p is AutocompleteOption => !!p);
/** AutocompleteRecipients — "Send to" in a money app. Recent payees with
* avatars while empty; typing matches names and handles. Picking someone
* fills the field and arms the send button. Green. */
export function AutocompleteRecipients() {
const [to, setTo] = React.useState<AutocompleteOption | null>(null);
const [query, setQuery] = React.useState("");
return (
<Accent color="green" className="w-full">
<View className="w-full gap-5">
<View className="items-center gap-1">
<Text variant="muted">Sending</Text>
<Text className="text-5xl font-semibold tracking-tight tabular-nums">£64.50</Text>
<Text variant="muted">Groceries and energy, October</Text>
</View>
<Autocomplete
value={query}
onValueChange={(q) => {
setQuery(q);
setTo(null);
}}
options={PEOPLE}
recent={RECENT}
recentTitle="Recent payees"
onSelect={setTo}
placeholder="Name, @handle or phone"
emptyText={(q) => `Nobody called "${q}" yet. Invite them by phone number.`}
/>
<Button size="lg" className="w-full" disabled={!to}>
{to ? `Send £64.50 to ${to.title.split(" ")[0]}` : "Choose who to pay"}
</Button>
</View>
</Accent>
);
} API reference
value string Controlled query text.
—defaultValue string Uncontrolled initial query.
"" onValueChange (query: string) => void Fires on every keystroke (debounce in your fetcher if remote).
—options AutocompleteOption[] Candidate options. Filtered by the built-in ranking unless filter is false (then pass already-filtered results).
[] filter ((options: AutocompleteOption[] …
((options: AutocompleteOption[], query: string) => AutocompleteOption[]) | false Custom filter, or false to show options as-is (remote search).
recent AutocompleteOption[] Shown while the query is empty.
—recentTitle string Header above recents. Default "Recent".
"Recent" onClearRecent () => void Shows a "Clear" action on the recent header.
—resultsTitle string Header above matches. Omit for none.
—onSelect (option: AutocompleteOption) => void Fires when a suggestion is picked.
—fillOnSelect boolean Fill the field with the picked title. Default true.
true loading boolean Skeleton rows while results load.
—maxResults number Max rows shown. Default 6.
6 minChars number Characters before matching starts. Default 1.
1 highlightMatch boolean Bold the typed part of each title. Default true.
true emptyText string | ((query: string) => string) Empty-results copy. Default No results for "<query>".
presentation "inline" | "dropdown" "inline" (default) list under the field, always visible; "dropdown" floating card shown while the field is focused.
"inline" open boolean Controlled suggestion visibility.
—onOpenChange (open: boolean) => void Fires when suggestions open/close (focus, pick, blur).
—placeholder string Field placeholder. Default "Search".
"Search" label string Label above the field.
—inputProps Omit<SearchInputProps, "value" …
Omit<SearchInputProps, "value" | "onChangeText" | "placeholder" | "label"> Extra props for the SearchInput field.
—emptyQueryContent React.ReactNode Content shown under recents while the query is empty (shortcuts).
—className string —