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.
Input
Labelled text field that lights up on focus, draws a check when you mark the value as good, and gives one quick flicker on error. Supports helper text, icons and a fill-as-you-type underline.
Preview
import * as React from "react";
import { forwardRef, useEffect, useId, useRef } from "react";
import { Platform, TextInput, View, Text, type TextInputProps } from "react-native";
import Animated, {
Easing,
FadeOut,
useSharedValue,
useAnimatedStyle,
useAnimatedProps,
withSpring,
withTiming,
interpolateColor,
} from "react-native-reanimated";
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
import { cn, ease, spring, timing, useReducedMotion, useTheme, AnimatedPath, AnimatedTextInput } from "@lumioui/core";
import { Glass } from "../glass";
/** Lumio check on the 24 grid — short stroke, long stroke (length ≈17.7). */
const SUCCESS_PATH = "M6 12.5l4 4 8-9";
const CHECK_LEN = 18;
/** Error flicker — the field kicks this far and releases into
* spring.shake: one decaying tremor, never a loop. */
const FLICKER_KICK = 4;
/** Field state colour shift — border + halo (focus, error and success all
* crossfade, nothing snaps). Quick enough to answer a tap into the field. */
const STATE_COLOR = { duration: timing.fast.duration, easing: Easing.bezier(...ease.inOut) };
/** Message line — the helper/error text ignites with a small drop from the
* field above it. */
const MESSAGE_IN = { duration: timing.fast.duration, easing: Easing.bezier(...ease.out) };
const MESSAGE_DROP = 3;
/** Success check draw — 240ms on the ignite curve, no beat in front. */
const CHECK_DRAW = { duration: 240, easing: Easing.bezier(...ease.out) };
/** Keyboard focus halo (web only) — a soft 2px ring just outside the border. */
const HALO_OPACITY = 0.35;
/** Focus light — the accent pours in from the field's top edge and fades out
* by this share of its height; peak alpha at the edge. */
const FOCUS_LIGHT_REACH = 0.6;
const FOCUS_LIGHT_ALPHA = 0.12;
/** Charge baseline — a filled-but-wrong field dims it back to this. */
const BASELINE_ERROR_DIM = 0.35;
/** Baseline geometry (pt) — 2px tall, matching the text box's side padding. */
const BASELINE_INSET = { bottom: 6, height: 2, flat: 14, glass: 16, icon: 40 } as const;
/*
* Keyboard modality (web) — the halo is for people tabbing through a form, so
* it only shows when focus arrived from the keyboard. One pair of document
* listeners, installed on first use.
*/
let keyboardModality = false;
let modalityInstalled = false;
type ModalityTarget = {
addEventListener: (type: string, fn: (e: { key?: string }) => void, capture?: boolean) => void;
};
function installModality() {
if (modalityInstalled || Platform.OS !== "web") return;
const doc = (globalThis as { document?: ModalityTarget }).document;
if (!doc) return;
modalityInstalled = true;
doc.addEventListener(
"keydown",
(e) => {
if (e.key === "Tab") keyboardModality = true;
},
true
);
doc.addEventListener(
"pointerdown",
() => {
keyboardModality = false;
},
true
);
}
export interface InputProps extends Omit<TextInputProps, "className"> {
/** Visible label above the field. */
label?: string;
/** Helper text below the field. */
helper?: string;
/** Error message — turns the field red, flickers it, and announces to screen readers. */
error?: string;
/** Shows an animated success check on the right edge. */
success?: boolean;
/** Icon node rendered inside the left edge of the field. */
leftIcon?: React.ReactNode;
/** Icon node rendered inside the right edge (hidden while the success check shows). */
rightIcon?: React.ReactNode;
/** Reserve one helper line even when empty — prevents layout shift on error. */
reserveHelperLine?: boolean;
/** Field density — "sm" for toolbars and dense forms, "md" (default) for
* full-size fields. */
size?: "sm" | "md";
/** NativeWind classes for the input element. */
className?: string;
/** Classes for the outer wrapper. */
containerClassName?: string;
/** Glass field — capsule material instead of the flat fill. */
glass?: boolean;
/** 0–1: how close the value is to valid (e.g. postcode chars / 6). Shows a
* 2px baseline under the text that charges as you type; omit for none. */
validity?: number;
}
/**
* Input — label + helper + error states, error flicker, drawn success check,
* icon slots. Minimum 44pt/48dp height per platform guidelines.
*
* Light follows input: focus lights the field from above (a 1px lit top edge
* and a fall of accent light over timing.fast) while the label goes from
* muted to ink. With `validity`, a 2px baseline fills left to right on
* spring.glide as the value nears valid; at valid it completes, retints to
* success and the check draws (240ms). An error flickers once and dims the
* baseline back. The halo shows for keyboard focus on web only. None of it
* changes the field's dimensions.
*/
export const Input = forwardRef<React.ElementRef<typeof TextInput>, InputProps>(
function Input(
{
label,
helper,
error,
success = false,
leftIcon,
rightIcon,
size = "md",
reserveHelperLine = false,
className,
containerClassName,
glass = false,
validity,
editable = true,
onFocus,
onBlur,
style,
...props
},
ref
) {
const { colors } = useTheme();
const reducedMotion = useReducedMotion();
const describedBy = error ?? helper;
// Built-in label gets a stable nativeID so the field can point back at
// it via accessibilityLabelledBy (Android) / aria-labelledby (web) —
// the same path Form.Label uses when wired through nativeID.
const autoId = useId();
const labelId = `${autoId}-label`;
useEffect(installModality, []);
const gradId = `${autoId.replace(/[^a-zA-Z0-9]/g, "")}light`;
const translateX = useSharedValue(0);
/** Keyboard focus (web) — the only thing that raises the halo. */
const kbdT = useSharedValue(0);
/** Baseline charge 0–1 — validity, completed by success. */
const chargeTarget = success && !error ? 1 : Math.min(1, Math.max(0, validity ?? 0));
const charge = useSharedValue(chargeTarget);
const hasBaseline = validity !== undefined;
/** Focus progression — drives the border color glide and halo ring. */
const focusT = useSharedValue(0);
/** Error/helper text entrance: 0 hidden → 1 visible. */
const msgT = useSharedValue(error || helper ? 1 : 0);
/** Error colour progression — border + halo crossfade to destructive. */
const errT = useSharedValue(error ? 1 : 0);
/** Success colour progression — border crossfades to success. */
const okT = useSharedValue(success && !error ? 1 : 0);
/** Success check draw progress. */
const checkDraw = useSharedValue(success ? 1 : 0);
const hadError = useRef(!!error);
const showSuccess = success && !error;
/** Which message kind is on the line — a helper → error swap re-runs the
* entrance so the error ignites fresh rather than recolouring in place. */
const msgKind = error ? "error" : helper ? "helper" : "none";
const prevKind = useRef(msgKind);
useEffect(() => {
if (error && !hadError.current) {
if (!reducedMotion) {
// One flicker: kick, then the flicker spring rings it out.
translateX.value = FLICKER_KICK;
translateX.value = withSpring(0, spring.shake);
}
hadError.current = true;
} else if (!error) {
hadError.current = false;
}
errT.value = reducedMotion ? (error ? 1 : 0) : withTiming(error ? 1 : 0, STATE_COLOR);
}, [error, errT, translateX, reducedMotion]);
useEffect(() => {
const changed = prevKind.current !== msgKind;
prevKind.current = msgKind;
const target = msgKind === "none" ? 0 : 1;
if (reducedMotion) {
msgT.value = target;
return;
}
// A new message kind ignites again; leaving dims fast (exits faster
// than entrances).
if (changed && target === 1) msgT.value = 0;
msgT.value =
target === 1
? withTiming(1, MESSAGE_IN)
: withTiming(0, { duration: timing.recede.duration, easing: Easing.bezier(...ease.in) });
}, [msgKind, msgT, reducedMotion]);
useEffect(() => {
const target = success && !error ? 1 : 0;
okT.value = reducedMotion ? target : withTiming(target, STATE_COLOR);
// The check only ever draws on — clearing resets it unseen (the slot
// unmounts), so a re-success always draws from zero.
checkDraw.value = target === 0 || reducedMotion ? target : withTiming(1, CHECK_DRAW);
}, [success, error, checkDraw, okT, reducedMotion]);
useEffect(() => {
charge.value = reducedMotion ? chargeTarget : withSpring(chargeTarget, spring.glide);
}, [chargeTarget, charge, reducedMotion]);
const fieldAnim = useAnimatedStyle(() => ({
transform: [{ translateX: translateX.value }],
}));
// Border color glides input → ring on focus; error/success win outright.
// Lives on the input itself (the flicker wrapper has no border).
// Every state crossfades: input → ring on focus, then success and error
// layered on top (error wins), each on its own timed progression.
const borderStyle = useAnimatedStyle(() => {
const focusC = interpolateColor(focusT.value, [0, 1], [colors.input, colors.ring]);
const okC = interpolateColor(okT.value, [0, 1], [focusC, colors.success]);
return { borderColor: interpolateColor(errT.value, [0, 1], [okC, colors.destructive]) };
});
// Halo — a faint 2px ring just outside the border, keyboard focus only.
const haloStyle = useAnimatedStyle(() => ({
opacity: kbdT.value * HALO_OPACITY,
borderColor: interpolateColor(errT.value, [0, 1], [colors.ring, colors.destructive]),
}));
// Light from above — the lit top edge and its fall-off follow focus.
const lightStyle = useAnimatedStyle(() => ({ opacity: focusT.value * (1 - errT.value) }));
// Label: muted at rest, ink while the field is lit, red with an error.
const labelStyle = useAnimatedStyle(() => ({
color: interpolateColor(
errT.value,
[0, 1],
[interpolateColor(focusT.value, [0, 1], [colors.mutedForeground, colors.foreground]), colors.destructive]
),
}));
// Baseline — fills from the leading edge; accent → success at valid; an
// error dims it back.
const baselineStyle = useAnimatedStyle(() => ({
opacity: 1 - errT.value * (1 - BASELINE_ERROR_DIM),
backgroundColor: interpolateColor(okT.value, [0, 1], [colors.primary, colors.success]),
transform: [{ scaleX: Math.max(0.0001, charge.value) }],
}));
const msgStyle = useAnimatedStyle(() => ({
opacity: msgT.value,
transform: [{ translateY: reducedMotion ? 0 : (1 - msgT.value) * -MESSAGE_DROP }],
}));
const checkProps = useAnimatedProps(() => ({
strokeDashoffset: (1 - checkDraw.value) * CHECK_LEN,
}));
const showRight = !!rightIcon || showSuccess;
const message = error ?? helper;
const showLine = !!message || reserveHelperLine;
// Reserved line: keep the last text painted while it fades out, so a
// cleared error recedes (exit) instead of blinking away. Hidden from
// screen readers — it is no longer the field's state.
const lastMessage = useRef<{ text: string; isError: boolean } | null>(null);
if (message) lastMessage.current = { text: message, isError: !!error };
const stale = !message && reserveHelperLine ? lastMessage.current : null;
return (
<View className={cn("gap-1.5", containerClassName)}>
{label ? (
<Animated.Text
nativeID={labelId}
className="text-sm font-medium"
style={labelStyle}
accessibilityRole="text"
>
{label}
</Animated.Text>
) : null}
{/* Disabled dim goes on the field wrapper — on web the input's own
opacity-50 loses to a placeholder-shown preflight rule. */}
<Animated.View
style={fieldAnim}
className={cn("justify-center", glass ? "rounded-full" : "rounded-xl", !editable && "opacity-50")}
>
{glass ? (
<Glass
effect="regular"
className="absolute inset-0 rounded-full"
pointerEvents="none"
/>
) : null}
{/* Focus halo — floats 3px outside the border, fades with focusT.
Skipped on glass fields: the material's own rim plus this ring
reads as a double outline. */}
{glass ? null : (
<Animated.View
pointerEvents="none"
style={[
{
position: "absolute",
top: -3,
left: -3,
right: -3,
bottom: -3,
borderRadius: 15,
borderWidth: 2,
},
haloStyle,
]}
/>
)}
{leftIcon ? (
<View className="absolute left-3 top-0 h-full items-center justify-center z-10" pointerEvents="none">
{leftIcon}
</View>
) : null}
{/* AnimatedTextInput is the shared className-registered primitive —
a drop-in TextInput accepting the same props + className + style. */}
<AnimatedTextInput
ref={ref}
editable={editable}
placeholderTextColor={colors.mutedForeground}
style={[borderStyle, style]}
onFocus={(e) => {
focusT.value = reducedMotion ? 1 : withTiming(1, STATE_COLOR);
kbdT.value = keyboardModality ? withTiming(1, STATE_COLOR) : 0;
onFocus?.(e);
}}
onBlur={(e) => {
focusT.value = reducedMotion ? 0 : withTiming(0, STATE_COLOR);
kbdT.value = withTiming(0, STATE_COLOR);
onBlur?.(e);
}}
className={cn(
// 48px = 44pt+ touch target; px-3.5 aligns text to 14px grid.
// Constant border-[1.5px] in every state — width never flickers;
// the color itself is animated (borderColor lives in fieldAnim).
size === "sm"
? glass
? "h-11 rounded-full border-[1.5px] border-transparent bg-transparent px-4 text-sm text-foreground"
: "h-11 rounded-xl border-[1.5px] border-transparent bg-background px-3 text-sm text-foreground"
: glass
? "h-12 rounded-full border-[1.5px] border-transparent bg-transparent px-4 text-base text-foreground"
: "h-12 rounded-xl border-[1.5px] border-transparent bg-background px-3.5 text-base text-foreground",
leftIcon && "pl-10",
showRight && "pr-10",
className
)}
{...props}
accessibilityLabel={label ?? props.accessibilityLabel}
// Keep generated semantics authoritative so a caller cannot
// accidentally erase the field's label, error, or disabled state.
accessibilityLabelledBy={label ? labelId : props.accessibilityLabelledBy}
aria-labelledby={label ? labelId : props["aria-labelledby"]}
accessibilityHint={describedBy ?? props.accessibilityHint}
accessibilityState={{ ...props.accessibilityState, disabled: !editable }}
// accessibilityState isn't forwarded to the DOM on web — mirror
// the error with an explicit aria-invalid like Checkbox does.
aria-invalid={!!error || (props as TextInputProps & { "aria-invalid"?: boolean })["aria-invalid"] === true}
/>
{/* Light from above — lit top edge + accent fall-off inside the
field shape, over the fill. Decorative. */}
<Animated.View
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
className={cn("absolute inset-0 overflow-hidden", glass ? "rounded-full" : "rounded-xl")}
style={lightStyle}
>
<Svg width="100%" height="100%">
<Defs>
<LinearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
<Stop offset={0} stopColor={colors.primary} stopOpacity={FOCUS_LIGHT_ALPHA} />
<Stop offset={FOCUS_LIGHT_REACH} stopColor={colors.primary} stopOpacity={0} />
</LinearGradient>
</Defs>
<Rect x="0" y="0" width="100%" height="100%" fill={`url(#${gradId})`} />
</Svg>
<View className="absolute left-0 right-0 top-0 h-px bg-primary" />
</Animated.View>
{hasBaseline ? (
<View
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
className="absolute overflow-hidden rounded-full bg-border"
style={{
bottom: BASELINE_INSET.bottom,
height: BASELINE_INSET.height,
// Sits under the text: same leading/trailing inset as the text box.
left: leftIcon ? BASELINE_INSET.icon : glass ? BASELINE_INSET.glass : BASELINE_INSET.flat,
right: showRight ? BASELINE_INSET.icon : glass ? BASELINE_INSET.glass : BASELINE_INSET.flat,
}}
>
<Animated.View className="h-full w-full rounded-full" style={[{ transformOrigin: "left" }, baselineStyle]} />
</View>
) : null}
{showRight ? (
<View className="absolute right-3 top-0 h-full items-center justify-center" pointerEvents="none">
{showSuccess ? (
<Svg width={18} height={18} viewBox="0 0 24 24" fill="none">
<AnimatedPath
d={SUCCESS_PATH}
stroke={colors.success}
strokeWidth={3}
strokeLinecap="round"
strokeLinejoin="round"
strokeDasharray={CHECK_LEN}
animatedProps={checkProps}
/>
</Svg>
) : (
rightIcon
)}
</View>
) : null}
</Animated.View>
{showLine ? (
// Unmounting line (no reserve) recedes instead of vanishing.
<Animated.View style={[{ minHeight: 20 }, msgStyle]} exiting={FadeOut.duration(timing.recede.duration)}>
{error ? (
<Text
className="text-sm text-destructive"
accessibilityLiveRegion="polite"
accessibilityRole="alert"
>
{error}
</Text>
) : helper ? (
<Text className="text-sm text-muted-foreground">{helper}</Text>
) : stale ? (
<Text
className={cn("text-sm", stale.isError ? "text-destructive" : "text-muted-foreground")}
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
aria-hidden
>
{stale.text}
</Text>
) : null}
</Animated.View>
) : null}
</View>
);
}
);
Input.displayName = "Input"; import { Input } from "@/components/ui/input/input";
export function Example() {
return (
<Input />
);
} Installation
Install the dependencies
npx expo install react-native-reanimated react-native-svgAdd the components it builds on
Copy the source from the Code tab into your project
components/ui/input/input.tsxcomponents/ui/input/index.tsUpdate the import paths to match your project setup.
Usage
import { Input } from "@/components/ui/input/input"; <Input /> Examples
Shipping step of a fashion-retail checkout, ink only.
import * as React from "react";
import { View } from "react-native";
import { Input } from "../input";
import { Button } from "../../button/button";
import { Icon } from "../../icon/icon";
import { Text } from "../../text/text";
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
/** How far an email is from valid: a name, the @, a domain, a dot + ending. */
function emailCharge(v: string): number {
const at = v.indexOf("@");
if (at < 0) return v.length > 0 ? 0.3 : 0;
const domain = v.slice(at + 1);
const dot = domain.lastIndexOf(".");
return (
(at > 0 ? 0.3 : 0) +
0.2 +
Math.min(1, (dot > 0 ? dot : domain.length) / 4) * 0.25 +
(dot > 0 ? Math.min(1, (domain.length - dot - 1) / 2) * 0.25 : 0)
);
}
/** InputCheckout — shipping step of a fashion-retail checkout, ink only.
* Focus lights each field from above; the email and postcode baselines
* charge as you type and complete into the success check at valid. A
* malformed email flickers in an error, and the postcode only turns red
* once it is long enough to judge. The CTA unlocks when the form is complete. */
export function InputCheckout() {
const [email, setEmail] = React.useState("noor.haddad@");
const [name, setName] = React.useState("Noor Haddad");
const [street, setStreet] = React.useState("");
const [city, setCity] = React.useState("Harbourside");
const [zip, setZip] = React.useState("");
const emailOk = EMAIL_RE.test(email);
const emailError = email.length > 0 && !emailOk && !email.endsWith("@") ? "Check the address, it's missing a domain" : undefined;
const zipOk = /^\d{4}\s?[A-Za-z]{2}$/.test(zip.trim());
const zipError = zip.length >= 6 && !zipOk ? "Postcodes look like 3511 AB" : undefined;
const ready = emailOk && name.trim().length > 1 && street.trim().length > 3 && city.trim().length > 1 && zipOk;
return (
<View className="w-full gap-5 rounded-3xl bg-card p-5">
<View className="gap-1">
<Text className="text-2xl font-bold tracking-tight">Shipping</Text>
<Text variant="muted">2 items · Linen overshirt, Canvas tote</Text>
</View>
<View className="gap-1">
<Input
label="Email"
placeholder="[email protected]"
value={email}
onChangeText={setEmail}
autoCapitalize="none"
keyboardType="email-address"
leftIcon={<Icon name="mail" size="sm" color="mutedForeground" />}
error={emailError}
validity={emailCharge(email)}
helper="We'll send tracking here."
success={emailOk}
reserveHelperLine
/>
<Input
label="Full name"
value={name}
onChangeText={setName}
autoComplete="name"
reserveHelperLine
/>
<Input
label="Street and number"
placeholder="Lantern Quay 158"
value={street}
onChangeText={setStreet}
leftIcon={<Icon name="map-pin" size="sm" color="mutedForeground" />}
reserveHelperLine
/>
<View className="flex-row gap-3">
<Input
containerClassName="flex-1"
label="Postcode"
placeholder="3511 AB"
value={zip}
onChangeText={setZip}
autoCapitalize="characters"
error={zipError}
validity={Math.min(1, zip.replace(/\s/g, "").length / 6)}
success={zipOk}
reserveHelperLine
/>
<Input
containerClassName="flex-1"
label="City"
value={city}
onChangeText={setCity}
reserveHelperLine
/>
</View>
</View>
<Button size="lg" className="w-full" disabled={!ready}>
Continue to payment
</Button>
</View>
);
} A trip planner's route fields floating over the destination photo: start point and destination as glass capsules.
import * as React from "react";
import { Image, StyleSheet, View } from "react-native";
import { Input } from "../input";
import { Icon } from "../../icon/icon";
const PHOTO =
"https://images.unsplash.com/photo-1509316785289-025f5b846b35?w=800&h=1000&fit=crop&q=70&auto=format";
/** InputGlass — a trip planner's route fields floating over the destination
* photo: start point and destination as glass capsules. Glass is earned
* here because the field sits on photographic content, not a flat card. */
export function InputGlass() {
const [from, setFrom] = React.useState("Current location");
const [to, setTo] = React.useState("");
return (
<View className="relative h-[460px] w-full overflow-hidden rounded-3xl bg-muted">
<Image source={{ uri: PHOTO }} style={StyleSheet.absoluteFill} resizeMode="cover" accessibilityIgnoresInvertColors />
<View className="absolute inset-x-4 top-5 gap-2">
<Input
glass
value={from}
onChangeText={setFrom}
accessibilityLabel="Starting point"
leftIcon={<Icon name="pointer" size="sm" color="foreground" />}
/>
<Input
glass
value={to}
onChangeText={setTo}
placeholder="Destination"
accessibilityLabel="Destination"
leftIcon={<Icon name="map-pin" size="sm" color="foreground" />}
success={to.trim().length > 2}
/>
</View>
</View>
);
} API reference
label string Visible label above the field.
—helper string Helper text below the field.
—error string Error message — turns the field red, flickers it, and announces to screen readers.
—success boolean Shows an animated success check on the right edge.
false leftIcon React.ReactNode Icon node rendered inside the left edge of the field.
—rightIcon React.ReactNode Icon node rendered inside the right edge (hidden while the success check shows).
—reserveHelperLine boolean Reserve one helper line even when empty — prevents layout shift on error.
false size "sm" | "md" Field density — "sm" for toolbars and dense forms, "md" (default) for full-size fields.
"md" className string NativeWind classes for the input element.
—containerClassName string Classes for the outer wrapper.
—glass boolean Glass field — capsule material instead of the flat fill.
false validity number 0–1: how close the value is to valid (e.g. postcode chars / 6). Shows a 2px baseline under the text that charges as you type; omit for none.
—